如何启用 Kotlins“任意表达式的单位转换”

m.r*_*ter 5 kotlin

我收到 Kotlin 错误:

“任意表达式的单位转换”功能是实验性的,应明确启用。您还可以将此表达式的原始类型更改为 (...) -> Unit

我的代码如下:

val foo: () -> String = { "Test" }

fun bar(doSometing: () -> Unit) { /* */ }

val baz = bar(foo) // here foo throws the error
Run Code Online (Sandbox Code Playgroud)

很明显我做错了什么:bar期望() -> Unit,但我提供() -> String

但是,错误消息意味着我可以选择“任意表达式的单位转换”。我该怎么做呢?

我在这里找到的唯一相关的东西并没有回答我的问题:/sf/ask/5056683761/

k31*_*159 4

有趣的是,您可以传递函数引用,但不能传递等效表达式:

fun f(): String = "Test"
val foo = ::f
fun bar(doSometing: () -> Unit) { /* */ }

val baz = bar(::f)  // OK
val baz2 = bar(foo) // Error
Run Code Online (Sandbox Code Playgroud)

您可以使用命令行选项进行编译,
-XXLanguage:+UnitConversionsOnArbitraryExpressions但不建议这样做:

$ 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) { /* */ }
        ^
$ 
Run Code Online (Sandbox Code Playgroud)