如何使用Kotlin调用类似扩展方法的不同版本

时间:2019-03-21 11:11:50

标签: kotlin

我具有以下功能来模拟Kotlin的三元运算符

fun Boolean.then(action: () -> Unit): Boolean {
    if (this)
        action.invoke()
    return this
}

fun Boolean.otherwise(action: () -> Unit) {
    if (!this)
        action.invoke()
}

fun <T> Boolean.then(func: () -> T): T? {
    if (this)
        return func.invoke()
    return null
}

fun <T> T?.otherwise(action: () -> T): T {
    return this ?: action.invoke()
}

应该这样使用它们:

(check).then { doHello() }.otherwise { doWorld() }

val answer = (check).then { "hello" }.otherwise { "world" }

但是,当我尝试使用上述运算符分配值时,

 val visibility: Int = (show).then { View.VISIBLE }.alt { View.GONE }

我收到一条错误消息,要求的答复是Int,但实际上得到的是Unit,这意味着它调用了方法的第一个版本而不是第二个版本

除了重命名方法之外(当我将前两个更改为thenDo和elseDo起作用时),我是否可以通过某种方式编写上述代码,以便编译器知道调用第二个版本?

1 个答案:

答案 0 :(得分:2)

我认为您不需要两个重载。如果删除返回Unit的代码,则两行代码都可以工作:

(check).then { doHello() }.otherwise { doWorld() }
val answer = (check).then { "hello" }.otherwise { "world" }

这是因为第一行中,lambda返回Unit,例如doHello()仍可以使用thenotherwise的通用版本,因为它们仍被视为具有返回值即Unit的函数。

尽管我同意上面的一些评论:您真的需要这个吗?为什么不只使用if,它是一个返回值的表达式(如三元运算符)。有关更多信息,请参见讨论here

相关问题