I am learning Kotlin by doing exercises on exercism.com. I am currently working on triangles. The code has the following test that I'm trying to make pass:
class TriangleTest {
@Test(expected = IllegalArgumentException::class)
fun `triangle inequality violation - last is greater then sum of others `() {
Triangle(1, 1, 3)
}
}
My solution:
class Triangle<out T : Number>(private val a: T, private val b: T, private val c: T) {
init {
// ...
if (a b <= c) {
throw IllegalArgumentException()
}
}
}
IntelliJ highlights the
red and gives the following error:
Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public inline operator fun BigDecimal.plus(other: BigDecimal): BigDecimal defined in kotlin
public inline operator fun BigInteger.plus(other: BigInteger): BigInteger defined in kotlin
...
This goes on for like 100 lines with other plus()
methods from array and collection types.
Why can't I add two numbers in the init
block here?
CodePudding user response:
This is because Kotlin does not provide a plus
overload for adding two Number
s. One way is to convert the Number
s to Double
s add then perform operations on them. Also, Kotlin provides a handy require function for such validations.
class Triangle(val a: Number, val b: Number, val c: Number) {
init {
val (x, y, z) = listOf(a.toDouble(), b.toDouble(), c.toDouble())
require(x y > z)
}
}