Strings

Kotlin, like most other modern languages (Java included), has immutable strings. The same String class from Java is used in Kotlin, but Kotlin has quite a lot of extension methods in the standard library that add additional functionality to it.

But, there is one big difference from Java: equality comparison. Kotlin overrides the == operator so it can be used to compare Strings based on their value, not their reference (memory address). In Java, if you want to check if Strings are equal based on their value, you have to compare them with an equals method.

String variables are usually declared with String literals, which have to be enclosed in double quotes, as the following command shows:

val s: String = "Kotlin"

Another great thing with Strings in Kotlin is that String templating is supported. This means that you can insert variables or expressions inside String literals. In Java, you would have to concatenate Strings with the + operator, but in Kotlin you can create a String like this:

fun printPersonDetails(person: Person)
{
println("${person.name} was born in ${person.birthYear} year")
}

If a Person object is passed to this function with properties name = John and birthYear = 1990, this will print John was born in 1990 year

Finally, Kotlin supports raw String literals. They are declared with triple quotes and they have no escaping. A multiline raw String literal would be declared like this:

val multiLine: String = """
Hello Kotlin!
Nice to meet you!
"""
..................Content has been hidden....................

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