“Assignments are not expressions” error in Kotlin/

2019-09-22 09:32发布

问题:

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)
}

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

回答1:

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()
  }
})