Indexed access

The indexed access operator is the array read and write operations with square brackets ([]), that is used on languages with C-like syntax. In Kotlin, we use the get operators for reading and set for writing.

With the Pack.get operator, we can use Pack as an array:

operator fun Pack.get(name: String) = members[name]!!

val badWolf = biggerPack["Bad Wolf"]

Most of Kotlin data structures have a definition of the get operator, in this case, the Map<K, V> returns a V?.

The following table will show you different declarations of get with a different number of arguments:

Operator Equivalent Notes
x[y] x.get(y)
x[y1, y2] x.get(y1, y2)
x[y1, y2..., yN] x.get(y1, y2..., yN)

 

The set operator has similar syntax:

enum class WolfRelationships {
FRIEND, SIBLING, ENEMY, PARTNER
}

operator fun Wolf.set(relationship: WolfRelationships, wolf: Wolf) {
println("${wolf.name} is my new $relationship")
}

talbot[WolfRelationships.ENEMY] = badWolf
The operators get and set can have any arbitrary code, but it is a very well-known and old convention that indexed access is used for reading and writing. When you write these operators (and by the way, all the other operators too), use the principle of least surprise. Limiting the operators to their natural meaning on a specific domain, makes them easier to use and read in the long run.

The following table will show you different declarations of set with a different number of arguments:

Operator Equivalent Notes
x[y] = z x.set(y, z) Return value is ignored
x[y1, y2] = z x.set(y1, y2, z) Return value is ignored
x[y1, y2..., yN] = z x.set(y1, y2..., yN, z) Return value is ignored
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.181.252