我通过在exercism.com上做练习来学习Kotlin。我现在正在研究三角形。代码中有以下我试图通过的测试:
class TriangleTest {
@Test(expected = IllegalArgumentException::class)
fun `triangle inequality violation - last is greater then sum of others `() {
Triangle(1, 1, 3)
}
}
我的解决方案:
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突出显示+
红色并给出以下错误:
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
...
对于来自数组和集合类型的其他plus()
方法,这种情况持续了大约100行。
为什么我不能在这里的init
块中添加两个数字?
这是因为Kotlin没有为添加两个Number
提供plus
过载。一种方法是将Number
转换为Double
,然后对它们执行操作。此外,Kotlin还为此类验证提供了一个方便的require函数。
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)
}
}