String or String Array

#1

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?

#2

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”.

#3

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

Thanks a lot!