Kotlin: Specify input-constraints in interface

孤街浪徒 提交于 2020-05-15 06:22:04

问题


Lets say I have the following interface:

interface MathThing {

    fun mathFunction(x : Int)
}

Let's say the constraint I want to put onto this function is that x cannot be negative.

How can I make sure that every time this (or any other arbitrary) condition isn't met on a object of type MathThing, a (custom) exception is thrown?


回答1:


One way is to use a wrapper class for your function parameters. You can make an extension function so it's a little easier to pass values to the function.

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)
}


来源:https://stackoverflow.com/questions/61755258/kotlin-specify-input-constraints-in-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!