In Kotlin, is it possible to overload the following operation to x: X
?
x[i] = j
Currently, I can only see an indirect way, like defining some X.get
that returns an object of type XAtIndex
with a reference to the original, then defining XAtIndex.plugAssign
that modifies the original.
CodePudding user response:
If you want a =
that mutates an object instead of changing what is stored in a variable, you must implement plusAssign
on the type of the object returned by get()
. An example of this in the standard library is MutableList.plusAssign()
.
If you want the more traditional behavior of reassigning the value held at an index after creating a modified copy, your class should have matching get
and set
operator functions. Then you can implement a plus
function on whatever is the type of the get
/set
(if it doesn't have one). When =
is used, it will use the getter and setter operator functions along with the plus
operator of the type returned by get
. Example:
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)
}