可以说我有以下界面:
interface MathThing {
fun mathFunction(x : Int)
}
假设我要对此函数施加的约束是x不能为负。
我如何确定每次在MathThing类型的对象上不满足此(或任何其他任意)条件时,都会引发(自定义)异常?
一种方法是对函数参数使用包装器类。您可以创建扩展函数,以便将值传递给该函数要容易一些。
data class NonNegative(val value: Int) {
init{ if (value < 0) throw IllegalArgumentException("Input must not be negative.") }
}
fun Int.nonNegative() = NonNegative(this)
interface MathThing {
fun mathFunction(x : NonNegative)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句