繁体   English   中英

Kotlin中的SAM转换(Lambda表达式)

[英]SAM conversion in Kotlin (Lambda expression)

我在 Java 中定义了以下功能接口。

interface OnButtonSwitchedListener {
    fun onButtonSwitched(isLogin: Boolean)
}

现在,问题是当我必须在 Kotlin 中使用它时,我必须创建一个匿名的 object 才能像这样使用这个接口,

binding.button.setOnButtonSwitched(object: OnButtonSwitchedListener{
                    override fun onButtonSwitched(isLogin: Boolean) {
                        binding.root
                            .setBackgroundColor(
                                ContextCompat.getColor(
                                    this@AuthActivity,
                                     if(isLogin) R.color.colorPrimary else R.color.lb_secondPage))
                    }
                })

然而,语法是 Java8 更聪明,

binding.button.setOnButtonSwitched(isLogin -> {
                binding.root
                    .setBackgroundColor(
                        ContextCompat.getColor(
                        this,
                        isLogin ? R.color.colorPrimary : R.color.secondPage));
            })

有什么办法,我也可以在 Kotlin 中写出类似 lambda 的表达式吗?

我尝试了以下操作,但它引发了插图中显示的错误。

setOnButtonSwitched{isLogin -> {binding.root
                    .setBackgroundColor(
                        ContextCompat.getColor(
                            this@AuthActivity,
                            if(isLogin) R.color.colorPrimary else R.color.lb_secondPage))}}

Android Studio 中的错误消息

SAM 转换将在 Kotlin 1.4 中引入,在此之前您必须手动实现接口并暂时覆盖 function。

它们看起来和普通的 lambda 一样:

binding.button.setOnButtonSwitched{ isLogin ->
    ...
}

PS:Kotlin 1.4预计发布时间为Spring 2020


对于当前版本 Kotlin 1.3.xx

如果你经常使用这些,那么现在尝试创建一个实用程序 function:

fun OnButtonSwitchedListener(block: (Boolean) -> Unit) =
    object : OnButtonSwitchedListener {
        override fun onButtonSwitched(isLogin: Boolean) {
            block(isLogin)
        }
    }

现在你可以这样调用:

binding.button.setOnButtonSwitched(OnButtonSwitchedListener { isLogin ->
   ... // your code
})

假设接口实际上在 Java 中,而不是在 Kotlin 中( void onButtonSwitched(boolean isLogin)而不是fun onButtonSwitched(isLogin: Boolean) ),您需要删除 lambda 主体周围的{}isLogin ->之后的部分):

setOnButtonSwitched { isLogin -> binding.root
                    .setBackgroundColor(
                        ContextCompat.getColor(
                            this@AuthActivity,
                            if(isLogin) R.color.colorPrimary else R.color.lb_secondPage)) }

问题是您编写它的方式使 lambda 不调用 binding.root.setBackgroundColor binding.root.setBackgroundColor(...)而是创建另一个 lambda { binding.root.setBackgroundColor(...) }并将其丢弃。

暂无
暂无

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

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