如何启用 Kotlins "unit conversions on arbitrary expressions"



我得到一个Kotlin错误:

特征"任意表达式上的单位转换";是实验性的,应该明确启用。也可以更改该表达式的原始类型为(…)->单位

我的代码如下:
val foo: () -> String = { "Test" }
fun bar(doSometing: () -> Unit) { /* */ }
val baz = bar(foo) // here foo throws the error

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

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

我在SO上找到的唯一相关的东西没有回答我的问题:https://stackoverflow.com/questions/72238339/kotlin-the-feature-unit-conversion-is-disabled

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

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

你可以使用命令行选项
-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) { /* */ }
^
$ 

这是因为doSometing的预期类型是()->单位,但给定()->字符串,你可以通过修改foo的返回类型或者修改doSometing的类型来修复它

val foo: () -> Unit = { println("Test") }
fun bar(doSometing: () -> Unit) { doSometing() }
val baz = bar(foo)

.

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

工作好。

我有一个问题如果我只是这样做它不工作

val foo = { uiEvent: ScreenUiEvent ->
when (uiEvent) {
// some code
}
}

添加类型I didn't get any error

val foo: (ScreenUiEvent) -> Unit = { uiEvent ->
when (uiEvent) {
// some code
}
}

最新更新