Kotlin: 在接口中指定输入约束。

问题描述 投票:2回答:1

假设我有以下接口。

interface MathThing {

    fun mathFunction(x : Int)
}

假设我想在这个函数上设置的约束条件是x不能是负值。

我如何确保每次在MathThing类型的对象上不满足这个(或任何其他任意)条件时,都会抛出一个(自定义)异常?

validation kotlin exception interface defensive-programming
1个回答
2
投票

一种方法是为你的函数参数使用一个封装类。你可以做一个扩展函数,这样可以更容易地将值传递给函数。

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)
}
© www.soinside.com 2019 - 2024. All rights reserved.