简体   繁体   English

Kotlin中的Lambda表达式

[英]Lambda expressions in Kotlin

Consider the following Java class: 考虑以下Java类:

public class SomeClass {
    public interface Something {
        void doSomething();
    }

    public void call(Something something) {}
}

In Kotlin, I can use a lambda expression as follows: 在Kotlin中,我可以使用lambda表达式,如下所示:

SomeClass().call { 
    // do something
}

But if I define the following method in Kotlin (using the same interface): 但是如果我在Kotlin中定义以下方法(使用相同的接口):

fun call(something: Something) {}

Then this call: 然后这个电话:

call {
    // do something
}

Would generate a type mismatch error. 会产生类型不匹配错误。 Why? 为什么?

Kotlin only supports SAM conversions for Java methods, because Kotlin itself has function types. Kotlin仅支持Java方法的SAM转换,因为Kotlin本身具有函数类型。 Normally, Kotlin functions should be taking () -> Unit rather than Something . 通常,Kotlin函数应该是() -> Unit而不是Something If you really need it to take Something , you can use a SAM constructor: 如果你真的需要它来取Something ,你可以使用SAM构造函数:

call(Something { /* do something */ })

Any SAM type (Java interface with one abstract method) automatically gets such a constructor function that converts a lambda to its instance. 任何SAM类型(带有一个抽象方法的Java接口)都会自动获得将lambda转换为其实例的构造函数。

Kotlin requires that call takes something of interface something . Kotlin要求调用接受一些something

() -> Kotlin.Unit

Does not satisfy the type requirement. 不满足类型要求。

You can do this 你可以这样做

call (object : Something {
    override fun doSomething() {
        println("Passing an interface to call in kotlin!")
    }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM