简体   繁体   中英

"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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM