“分配不是表达". Kotlin/Android中的错误 [英] "Assignments are not expressions" error in 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()
将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
(请参见
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屋!