首页 文章

Kotlin lambda以Interface作为参数

提问于
浏览
1

我对Koltin lambdas有点困惑,我想知道如何使用它给出以下代码片段:

interface KotlinInterface {

    fun doStuff(str: String): String
}

并且需要将此接口作为参数传递的函数:

fun kotlinInterfaceAsArgument(kotlinInterface: KotlinInterface): String{

   return kotlinInterface.doStuff("This was passed to Kotlin Interface method")
}

fun main(args: Array<String>){

    val newString = kotlinInterfaceAsArgument({
      str -> str + " | It's here" //error here (type mismatch)
    })
}

但是,相同的逻辑但在Java中编译并按预期运行 .

public class JavaClass {

   public String javaInterfaceAsArgument(JavaInterface javaInterface){

        String passedToInterfaceMethod = "This was passed to Java Interface method";
        return javaInterface.doStuff(passedToInterfaceMethod);
    }

   public interface JavaInterface {

        public String doStuff(String str);
    }
}

public class Main {

    public static void main(String[] args) {

        JavaClass javaClass = new JavaClass();
        String newValue = javaClass.javaInterfaceAsArgument(str -> str + " | It's here!");

        System.out.println(newValue);
    }
}

在这种情况下,如何在Kotlin中使用lambda?

2 回答

  • 1

    SAM conversion(从1.1开始)仅适用于Java接口,而不适用于Kotlin接口 .

    另请注意,此功能仅适用于Java互操作;由于Kotlin具有适当的函数类型,因此不需要将函数自动转换为Kotlin接口的实现,因此不受支持 .

    您可以通过某些方法修复代码in this answer .

    Edit: 我意识到这与另一个问题完全相同,因为即使错误也是一样的 .

  • 2

    纯Kotlin的正确方法是使用高阶函数:https://kotlinlang.org/docs/reference/lambdas.html

    使用高阶函数,您可以将函数作为参数传递给它 .

    如果我们谈谈你的例子:

    fun kotlinFunctionAsArgument(kotlinFunction: (String) -> String): String {
        return kotlinFunction("This was passed to Kotlin Function method")
    }
    
    fun main(args: Array<String>){
        val newString = kotlinFunctionAsArgument({
            str -> str + " | It's here" //there are no errors
        })
    }
    

相关问题