You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 16:52:02