假设我有以下界面:
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)
}
关于validation - Kotlin:在界面中指定输入约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61755258/