String or String Array

from the CommonsWare Community archives

At April 18, 2019, 6:54pm, Shahood asked:

Hi,

I was looking at the following code snippet from Elements of Kotlin v0.1 - Pg 51

val things = listOf("foo", "bar", "goo")
things
  .filter { it[1]=='o' }
  .forEach { println(it) }

I’m unable to understand how it[1] returns the 2nd character. Is it, which actually is a string, being treated as a string array here?


At April 18, 2019, 10:35pm, mmurphy replied:

No.

In Java, String has the charAt() method, which returns the character for a given 0-based index.

Kotlin’s String instead has a get() function. It fills the same role as does charAt(), and I assume that “under the covers” that get() maps to charAt().

In Kotlin, though, a get(index: Int) function automatically enables [] as an alternative syntax. Wherever you see [] used with an Int index, that is really calling the get() function, passing in the index as a parameter. It is one of Kotlin’s bits of “syntactic sugar”.


At April 19, 2019, 4:18am, Shahood replied:

Wow, excellent info. Pl consider including it in the book if not mentioned elsewhere.

Thanks a lot!