3

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?

Moritz Groß
  • 1,352
  • 12
  • 30
  • Maybe use the unsigned integer instead. https://kotlinlang.org/docs/reference/basic-types.html#unsigned-integers – Animesh Sahu May 12 '20 at 15:13
  • This is just an easy example that I don't actually need. I want to know how any constraint can be enforced. But I will look up this class regardless. – Moritz Groß May 12 '20 at 15:15
  • In general interfaces can't enforce anything in their implementations. You add a comment saying that implementations should check that something is true. – al3c May 12 '20 at 15:56

1 Answers1

2

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)
}
Tenfour04
  • 83,111
  • 11
  • 94
  • 154