Composite data types
Let's discuss more complex types built into Kotlin. Some data types have major improvements compared to Java, while others are totally new.
Strings
Strings in Kotlin behave in a similar way as in Java, but they have a few nice improvements.
To start to access characters at a specified index, we can use theĀ indexing operator and access characters the same way we access array elements:
val str = "abcd" println (str[1]) // Prints: b
We also have access to various extensions defined in the Kotlin standard library, which make working with strings easier:
val str = "abcd" println(str.reversed()) // Prints: dcba println(str.takeLast(2)) // Prints: cd println("[email protected]".substringBefore("@")) // Prints: john println("[email protected]".startsWith("@")) // Prints: false
This is exactly the same String
class as in Java, so these methods are not part of String
class. They were defined as extensions. We will learn more about extensions in Chapter 7, Extension...