Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 494 Vote(s) - 3.57 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Kotlin - Override/Implement array-like accessor function

#1
Is it possible to override or implement the `[]` accessors in Kotlin (using operator overloading or similar)?

<!-- language: kotlin -->

val testObject = MyCustumObject()
println(testObject["hi"]) // i.e. implement this accessor.


In Python this is possible by implementing `__getitem__` and `__setitem__`.
Reply

#2
You have to override get().

[To see links please register here]


a[i] translates to a.get(i)
Reply

#3
As stated in [the documentation](

[To see links please register here]

) the `a[i]` is translated to `a.get(i)`. In example:

class MyObject {
operator fun get(ix:Int):String{
return "hello $ix"
}
}

Let's you write:

val a = MyObject()
println(a[123]) //-> "hello 123"

Similarly `a[i] = b` is translated to a method call `a.set(i, b)`.
Reply

#4
In Kotlin, it is [`get` and `set` operator functions](

[To see links please register here]

) that you need to implement:

class C {
operator fun get(s: String, x: Int) = s + x
operator fun set(x: Int, y: Int, value: String) {
println("Putting $value at [$x, $y]")
}
}

And the usage:

val c = C()
val a = c["123", 4] // "1234"
c[1, 2] = "abc" // Putting abc at [1, 2]



You can define `get` and `set` with arbitrary number of parameters for *indices* (at least one, of course); in addition, `set` has the expression which is assigned at the use site passed as its last argument:

* `a[i_1, ..., i_n]` is translated to `a.get(i_1, ..., i_n)`

* `a[i_1, ..., i_n] = b` is translated to `a.set(i_1, ..., i_n, b)`

`get` and `set` can have different overloads as well, for example:

class MyOrderedMap<K, V> {
// ...

operator fun get(index: Int): Pair<K, V> = ... // i-th added mapping
operator fun get(key: K): V = ... // value by key
}
<sup>Note: this example introduces undesirable ambiguity for `MyOrderedMap<Int, SomeType>` since both `get` functions will match calls like `m[1]`.</sup>
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through