Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What makes the String class in Kotlin to be able to work with square brackets?

In Kotlin you can do something like this:

val s: String = "Hey"
println(s[1])

or simply:

println("Hey"[1])

and you will print e.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But what if you want to extend this behavior to your own classes? What interface do you need to implement to accomplish this syntax?

I looked at String‘s supertypes and only found Comparable<String> and CharSequence, neither of which had any other supertypes themselves, so my quest ended early.

For example in Python, by defining a method called __getitem__ in a class, you can bestow the objects of that class the ability to be used with square brackets syntax like this a[i]; I was wondering how this was possible in Kotlin.

Thanks in advance.

>Solution :

You can use Kotlin’s operator overloading, specifically the overloading for indexed access operators.

The syntax "Hey"[1] is just an alias for "Hey".get(1) (if not on the left-hand side of an assignment, where it would be an alias for "Hey".set(1, ...)).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading