【问题标题】:Kotlin overloading operator index with assign other than setKotlin 重载运算符索引与赋值而不是集合
【发布时间】:2022-01-07 12:38:16
【问题描述】:

在Kotlin中,是否可以将以下操作重载为x: X

x[i] += j

目前,我只能看到一种间接的方式,比如定义一些X.get,返回一个XAtIndex类型的对象并引用原始,然后定义修改原始的XAtIndex.plugAssign

【问题讨论】:

    标签: kotlin operator-overloading


    【解决方案1】:

    如果您想要一个改变对象而不是更改存储在变量中的内容的+=,您必须在get() 返回的对象类型上实现plusAssign。标准库中的一个例子是MutableList.plusAssign()

    如果您想要在创建修改后的副本后重新分配索引中保存的值的更传统行为,您的类应该具有匹配的getset 运算符函数。然后,您可以在 get/set 的任何类型上实现 plus 函数(如果没有)。当使用+= 时,它将使用getter 和setter 运算符函数以及plus 返回的get 类型的运算符。示例:

    class Foo {
        private var thing1: String = "Hello"
        private var thing2: String = "World"
    
        operator fun get(thing: Int) = when (thing) {
            1 -> thing1
            2 -> thing2
            else -> throw IllegalArgumentException()
        }.also { println("get") }
    
        operator fun set(thing: Int, value: String) {
            when (thing) {
                1 -> thing1 = value
                2 -> thing2 = value
                else -> throw IllegalArgumentException()
            }
            println("set")
        }
    
        override fun toString(): String ="Foo(thing1='$thing1', thing2='$thing2')"
    
    }
    
    fun main() {
        val foo = Foo()
        foo[1] += "!!!"
        println(foo)
    }
    

    【讨论】:

    • When += is used, it will use the getter and setter operator functions along with the plus operator of the type returned by get 谢谢,我误以为它只会调用plusAssign。这解决了一切。
    • 如果可用,则使用 plusAssign()。但如果不是这样,它就会退回到传统行为。我认为他们甚至让您创建 plusAssign 并让它的行为与通常预期的 += 不同,这有点令人困惑。
    猜你喜欢
    • 1970-01-01
    • 2012-04-02
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多