如何将sam转换应用于我的匿名类实现并将其转换为lambda [英] How to apply sam conversion to my anonymous class implementation and convert it to lambda

查看:85
本文介绍了如何将sam转换应用于我的匿名类实现并将其转换为lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我可以使用匿名类来实现如下所示的接口:

In java I can use anonymous class to implement an interface like below:

接口:

interface Human
{
    void think();
}

实施:

public class  Runner
{
    public static void main(String[] args) 
    {
        Human programmer = new Human()
            { public void think()
                {
                    System.out.println("Hello World!");
                }

            };

            programmer.think()

    }
}

如果我将其转换为Kotlin,则它将变为:

And if i convert it to kotlin then it becomes:

接口:

interface Human
{
    fun think()
}

实施:

fun main(args: Array<String>)
{
    var programmer : Human = object : Human
                        {
                            override fun think()
                            {
                                System.out.println("Hello World!")  
                            }

                        }

        programmer.think()

}

但是我可以在kotlin实现中应用SAM(单一抽象方法)转换并转换为lamda吗?

But can i apply SAM(Single abstract method) conversion in the kotlin implementation and convert to lamda?

推荐答案

不,您不能将SAM转换用于Kotlin接口,只能用于Java接口. 有关SAM转换的官方文档(强调我的):

No, you can not use SAM conversion for Kotlin interfaces, only for Java interfaces. This is explicitly pointed out by official docs on SAM conversions (emphasis mine):

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

[SAM conversion] 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.

这篇关于如何将sam转换应用于我的匿名类实现并将其转换为lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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