Unfrapping Kotlin compiler error

Does anyone know why the following code does not work?

private fun wrapLogIfNeeded(buildMessageOnCurrentThread: Boolean, log: () -> String): () -> String
  return if(buildMessageOnCurrentThread) {
    val message = log() // Type mismatch: Required () -> String Found: Unit
    { message }
  }
  else {
     log
  }
}

But it does:

private fun wrapLogIfNeeded(buildMessageOnCurrentThread: Boolean, log: () -> String): () -> String
  return if(buildMessageOnCurrentThread) {
    val message = lazy { log() }.value
    { message }
  }
  else {
     log
  }
}
+4
source share
1 answer

This is due to the ambiguity of the syntax:

val message = log()
{ message }

This code is parsed as if it were val message = log() { message }, that is log, called with lambda { message }as an argument. And the instruction val message = ...has a type Unit, so an error message.

To solve this problem, you can add a semicolon:

val message = log();
{ message }
+6
source

Source: https://habr.com/ru/post/1674303/


All Articles