Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
463 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...