Kotlin Lambda,以Interface作为参数 [英] Kotlin lambda with Interface as an argument

查看:540
本文介绍了Kotlin Lambda,以Interface作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Koltin lambda感到困惑,并且我想知道如何使用给定的以下代码片段:

I'm a bit baffled by the Koltin lambdas and I wanted to know how to use it given the following snippet of code:

interface KotlinInterface {

    fun doStuff(str: String): String
}

以及需要将此接口作为参数传递的函数:

And the function that requires this Interface to be passed as a parameter:

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相同的逻辑可以按预期进行编译和运行.

However, the same logic but in Java compiles and runs as intended.

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?

How can I utilize lambda in Kotlin in this case?

推荐答案

SAM转换(自1.1版开始)仅适用于Java接口,不适用于Kotlin接口.

SAM conversion (as of 1.1) only works with Java interfaces, not Kotlin ones.

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

Also note that this feature works only for Java interop; since Kotlin has proper function types, automatic conversion of functions into implementations of Kotlin interfaces is unnecessary and therefore unsupported.

您可以在此答案中看到一些修复代码的方法.

我已经意识到这与另一个问题完全相同,甚至错误也相同.

I've realized this is an exact duplicate of the other question, as even the error is the same.

这篇关于Kotlin Lambda,以Interface作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆