“分配不是表达". Kotlin/Android中的错误 [英] "Assignments are not expressions" error in Kotlin/Android

查看:124
本文介绍了“分配不是表达". Kotlin/Android中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在以下代码中出现Assignments are not expressions, and only expressions are allowed in this context错误:

I'm getting a Assignments are not expressions, and only expressions are allowed in this context error on the following code:

private fun blankFields() {
    blank_fields_error.visibility = View.VISIBLE
    Handler().postDelayed(blank_fields_error.visibility = View.INVISIBLE, 5000)
}

如果将postDelayed()的第一个参数包装在{}中,则可以正常工作-但我试图理解为什么需要{}.

If I wrap the first parameter of postDelayed() in {} then it works fine - but I'm trying to understand why the {} are needed.

postDelayed()docs

推荐答案

postDelayed()Runnable作为其第一个参数. blank_fields_error.visibility = View.INVISIBLE不是Runnable.这是一个赋值语句.

postDelayed() takes a Runnable as its first parameter. blank_fields_error.visibility = View.INVISIBLE is not a Runnable. It is an assignment statement.

由于Runnable是用Java定义的接口,并且具有单个方法,因此您可以传递Kotlin lambda表达式作为第一个参数,并且Kotlin编译器会为您将其转换为Runnable(请参见"SAM转换" ).

Since Runnable is an interface defined in Java, and it has a single method, you can pass a Kotlin lambda expression as the first parameter, and the Kotlin compiler will convert that into a Runnable for you (see "SAM Conversions" in the Kotlin documentation).

因此,虽然blank_fields_error.visibility = View.INVISIBLE是赋值,但{blank_fields_error.visibility = View.INVISIBLE}是恰好执行赋值的lambda表达式.您可以将lambda表达式传递给postDelayed().

So, while blank_fields_error.visibility = View.INVISIBLE is an assignment, {blank_fields_error.visibility = View.INVISIBLE} is a lambda expression that happens to perform an assignment. You can pass the lambda expression to postDelayed().

对于在Java中您可能会使用匿名内部类,在扩展的接口或类具有多个方法的地方,在Kotlin中,您可以创建一个匿名对象:

For places where in Java you might use anonymous inner classes, where the interface or class being extended has more than one method, in Kotlin you can create an anonymous object:

someField.addTextChangedListener(object : TextWatcher {
  fun afterTextChanged(s: Editable) {
    TODO()
  }

  fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
    TODO()
  }

  fun onTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
    TODO()
  }
})

这篇关于“分配不是表达". Kotlin/Android中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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