本文介绍了如何使用 Kotlin 将函数输出转换为 Unit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Kotlin 中应该返回 Unit 的函数遇到问题,但由于使用了另一个返回布尔值的函数,存在类型不匹配.

I have troubles with a function in Kotlin that should return Unit, but due to a usage of another function returning a Boolean, there is a type mismatch.

这是一个人为的例子:

fun printAndReturnTrue(bar: Int): Boolean {
    println(bar)
    return true
}

fun foo(bar: Int): Unit = when(bar) {
    0 -> println("0")
    else -> printAndReturnTrue(bar)
}

在这里,我实际上并不关心 printAndReturnTrue 返回布尔值的事实.我只想 foo 执行副作用操作.但是编译器会警告类型不匹配:我的 else 应该返回一个 Unit 值.

Here, I actually do not care about the fact that printAndReturnTrue returns a boolean. I just want foo to perform side-effect operations. But the compiler warns about a type mismatch: my else should return a Unit value.

有没有一种将值转换为 Unit 的好方法?

Is there a nice way to convert a value to Unit?

我看到的最简单的解决方案是:

The simplest solutions I see are:

fun foo(bar: Int): Unit = when(bar) {
    0 -> println("0")
    else -> {
        printAndReturnTrue(bar)
        Unit
    }
}

或:

fun foo(bar: Int): Unit = when(bar) {
    0 -> println("0")
    else -> eraseReturnValue(printAndReturnTrue(bar))
}

fun eraseReturnValue(value: Any) = Unit

或者我使用全函数形式:

Or I use the full function form:

fun foo(bar: Int): Unit {
    when(bar) {
        0 -> println("0")
        else -> printAndReturnTrue(bar)
    }
}

我确信有一些惯用的方法可以做到这一点(或者是最后一个例子?),但现在我没有找到它们.

I am sure there are some idiomatic ways to do that (or is is the last example?), but for now I did not find them.

推荐答案

不幸的是,没有 惯用的 方法可以做到这一点.一个类似的问题,传递一个 (T) -> 类型的 lambda;Boolean 到接受 (T) -> 的函数单位 lambdas 之前已经出现过,那里需要的自动转换应该会在未来某个时候出现在该语言中.

Unfortunaly, there's no idiomatic way to do this. A similiar problem, passing a lambda of type (T) -> Boolean to a function accepting (T) -> Unit lambdas has come up before, and the auto conversion required there is supposed to come to the language at some future point.

现在,您可以在 when 表达式的末尾使用扩展函数将其强制转换为 Unit 值:

For now, you could use an extension function at the end of the when expression to coerce it back into a Unit value:

fun Any?.toUnit() = Unit

fun foo(bar: Int): Unit = when(bar) {
    0 -> println("0")
    else -> printAndReturnTrue(bar)
}.toUnit()

或者,一个扩展属性,如果你碰巧更喜欢它:

Alternatively, an extension property, if you happen to like that better:

val Any?.unit get() = Unit

fun foo(bar: Int): Unit = when(bar) {
    0 -> println("0")
    else -> printAndReturnTrue(bar)
}.unit

当然,如果你使用其中任何一个,你可以省略函数的显式 Unit 返回类型.

Of course you can omit the explicit Unit return type of the function if you use either of these.

这篇关于如何使用 Kotlin 将函数输出转换为 Unit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 19:52
查看更多