postDelayed()
takes a Runnable
as its first parameter. blank_fields_error.visibility = View.INVISIBLE
is not a 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).
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()
.
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()
}
})
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…