Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

"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

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...