Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Specify input-constraints in interface

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?

like image 815
Moritz Groß Avatar asked Aug 03 '26 21:08

Moritz Groß


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)
}
like image 51
Tenfour04 Avatar answered Aug 07 '26 01:08

Tenfour04