如何使覆盖单表达式函数的返回类型为Unit?
问题描述:
如何覆盖返回void
或Unit
的函数,其中single-expression function的表达式返回某些非Unit
类型?例如:如何使覆盖单表达式函数的返回类型为Unit?
interface Base {
fun overrideMe(): Unit
}
class Derived: Base {
override fun overrideMe() = runAsync { }
}
答
思前想后,我发现在顶层为覆盖单表达功能的最佳方法是使用let
返回一个Unit
,然后无需else从句在所有,例如:
class Derived : Base {
// v--- uses `let` here
override fun overrideMe()=let{if (Math.random() < 0.5) runAsync { /*TODO*/ }}
}
OR使用如果表达让在,例如:
class Derived : Base {
// use let to return Unit explicitly , but I think T.let{Unit} is more clearly
// and the Unit is optional you can do it as T.let{} simply ---v
override fun overrideMe() = if (Math.random() < 0.5) runAsync { }.let { Unit }
else Unit
}
或使得Unit
在下面的最后一条语句:
class Derived : Base {
// return Unit explicitly ---v
override fun overrideMe() = if (Math.random() < 0.5){ runAsync { }; Unit }
else Unit
}
答
您可以通过在kotlin-stdlib
使用的功能之一做出任何表情Unit
:
override fun foo() = someExpression.let { }
override fun foo() = Unit.apply { someExpression }
或者以任何方式编写您自己的扩展程序fun Any.toUnit(): Unit = ...
,然后使用它。
这不起作用。注意'foo()'不会覆盖示例中的任何内容。 – breandan
@brendan嗨,请举个简单的例子。 –
当然,请看上面的例子。 – breandan