I'm getting a Kotlin Error:
The feature "unit conversions on arbitrary expressions" is experimental and should be enabled explicitly. You can also change the original type of this expression to (...) -> Unit
My code is the following:
val foo: () -> String = { "Test" }
fun bar(doSometing: () -> Unit) { /* */ }
val baz = bar(foo) // here foo throws the error
It's pretty obvious what i'm doing wrong: bar
expects () -> Unit
, but i provide () -> String
.
However, the error message implies i can opt in to "unit conversions on arbitrary expressions". How do i do this?
The only thing related i could find here on SO doesn't answer my question: https://stackoverflow.com/questions/72238339/kotlin-the-feature-unit-conversion-is-disabled
CodePudding user response:
It's interesting that you can pass a function reference but not an equivalent expression:
fun f(): String = "Test"
val foo = ::f
fun bar(doSometing: () -> Unit) { /* */ }
val baz = bar(::f) // OK
val baz2 = bar(foo) // Error
You can make it compile using the command-line option
-XXLanguage: UnitConversionsOnArbitraryExpressions
but it's not recommended:
$ cat t.kt
val foo: () -> String = { "Test" }
fun bar(doSometing: () -> Unit) { /* */ }
val baz = bar(foo)
$ kotlinc t.kt
t.kt:5:15: error: the feature "unit conversions on arbitrary expressions" is experimental and should be enabled explicitly. You can also change the original type of this expression to (...) -> Unit
val baz = bar(foo)
^
$ kotlinc -XXLanguage: UnitConversionsOnArbitraryExpressions t.kt
warning: ATTENTION!
This build uses unsafe internal compiler arguments:
-XXLanguage: UnitConversionsOnArbitraryExpressions
This mode is not recommended for production use,
as no stability/compatibility guarantees are given on
compiler or generated code. Use it at your own risk!
t.kt:3:9: warning: parameter 'doSometing' is never used
fun bar(doSometing: () -> Unit) { /* */ }
^
$