如何修复Kotlin嵌套接口中的加法运算错误?
问题修复方案
错误原因
你的Integer类错误地添加了泛型声明<Int>,这会让Kotlin把类里的x、value的类型识别为泛型参数Int(而非Kotlin内置的Int类型)。泛型参数本身没有定义+运算,所以编译器无法解析this.value + other.value的操作。
修复步骤
- 移除
Integer类的泛型声明<Int>,让它直接使用外部Z类实现Semigroup<Int>时指定的Int类型 - 可选优化:因为
Integer类不需要访问外部Z类的成员,可以把inner class改成class,避免不必要的外部类引用
修复后的完整代码
interface T1 interface Semigroup<T1> { fun builder(x: T1): SemigroupElement<T1> interface SemigroupElement<T1> { fun multiply(other: SemigroupElement<T1>): SemigroupElement<T1> val value: T1 } } fun main() { class Z : Semigroup<Int> { override fun builder(x: Int): Semigroup.SemigroupElement<Int> = Integer(x) class Integer(val x: Int) : Semigroup.SemigroupElement<Int> { override val value = x override fun multiply(other: Semigroup.SemigroupElement<Int>): Semigroup.SemigroupElement<Int> { return Integer(this.value + other.value) } } } }
内容的提问来源于stack exchange,提问作者zplot
相关产品推荐
相关产品推荐

