Search code examples
androidrx-javakotlinrx-java2rx-kotlin

For a Kotlin function used as an expression, is there concise way to operate on and return a value?


In Kotlin the final statement of a function can be interpreted as its return value.

Can a situation like the following example be simplified to be less verbose?

{ text: String ->
  val validated = validateText(text)
  if (validated) {
    actOnValidation()
  }
  validated
}

A concrete case where I would like to do this is below in an example using RxJava - even if there's a better Rx approach I'm also interested in a pure Kotlin solution if it exists.

fun inputChainObservable(targetField: TextView, chainedField: TextView): Observable<Boolean> {
  return targetField.textChanges()
      .observeOn(AndroidSchedulers.mainThread())
      .map { cs: CharSequence? ->
        val hasInput = validateText(cs.toString())
        if (hasInput) {
          chainedField.requestFocus()
        }
        hasInput
      }
}

Solution

  • You can use also() to operate on and return the receiver:

    { text: String ->
        validateText(text).also { valid ->
            if (valid) actOnValidation()
        }
    }
    

    You can also write it like this, but I prefer the first form because I think it's clearer:

    { text: String ->
        validateText(text).also {
            if (it) actOnValidation()
        }
    }