Kotlin: Specify input-constraints in interface

Viewed 269

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 Answers

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