[英]"Assignments are not expressions" error in Kotlin/Android
I'm getting a Assignments are not expressions, and only expressions are allowed in this context
error on the following code:我得到一个
Assignments are not expressions, and only expressions are allowed in this context
在以下代码的Assignments are not expressions, and only expressions are allowed in this context
错误中Assignments are not expressions, and only expressions are allowed in this context
:
private fun blankFields() {
blank_fields_error.visibility = View.VISIBLE
Handler().postDelayed(blank_fields_error.visibility = View.INVISIBLE, 5000)
}
If I wrap the first parameter of postDelayed()
in {}
then it works fine - but I'm trying to understand why the {}
are needed.如果我将
postDelayed()
的第一个参数包装在{}
那么它工作正常 - 但我试图理解为什么需要{}
。
postDelayed()
takes a Runnable
as its first parameter. postDelayed()
将Runnable
作为其第一个参数。 blank_fields_error.visibility = View.INVISIBLE
is not a Runnable
. blank_fields_error.visibility = View.INVISIBLE
不是Runnable
。 It is an assignment statement.它是一个赋值语句。
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 ).由于
Runnable
是在 Java 中定义的接口,并且它只有一个方法,因此您可以将 Kotlin lambda 表达式作为第一个参数传递,Kotlin 编译器会为您将其转换为Runnable
(请参阅Kotlin 文档中的“SAM 转换” )。
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.因此,虽然
blank_fields_error.visibility = View.INVISIBLE
是一个赋值,但{blank_fields_error.visibility = View.INVISIBLE}
是一个恰好执行赋值的 lambda 表达式。 You can pass the lambda expression to postDelayed()
.您可以将 lambda 表达式传递给
postDelayed()
。
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:对于在 Java 中可能使用匿名内部类的地方,在被扩展的接口或类具有多个方法的地方,在 Kotlin 中,您可以创建一个匿名对象:
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()
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.