Kotlin Tutorial
Kotlin Classes
Strings:
In Kotlin, Strings data type is represented by the type String, and is used to store a sequence of characters e.g some text. String values must go inside double quotes “:
Example:
fun main(args: Array) {
val myStringLetters: String = "Hello World Strings"
println(myStringLetters)
}
The code above outputs:
Hello World Strings
Strings Immutability:
Strings are immutable. You cannot change the string value once initialized. There are many operations that transform strings, and return their results in a new String object, leaving the original string unchanged.
Example:
fun main(args: Array) {
val s1: String = "abCdEfG"
println(s1.uppercase())
println(s1.lowercase())
println(s1)
}
The code above outputs:
ABCDEFG // uppercase
Abcdefg // lowercase
abCdEfG // original string
Strings Concatenation:
Concatenation of Strings can be done by an operator “+”. You can either concatenate Strings or different types of values with String.
Example
// String with String
val s1 = "Kotlin is" + " Best"
println(s1);
// String + Int
val s2 = "Kotlin is " + 1 + " of the best language"
println(s2)
// String + Double
val s3 = "1 + 0.1 results in " + 1.1
println(s3)
// or You also can do
val s4 = "Kotlin is "
println(s4 + "Modern language")
The code above outputs:
Kotlin is Best
Kotlin is 1 of the best language
1 + 0.1 results in 1.1
Kotlin is Modern language
String Literals:
Kotlin got two types of string literals:
- Escaped strings
- Raw strings
Escaped strings
Escaped strings can either contain escaped characters or not.
Example:
// String contain escaped characters
val s1 = "Kotlin is\nlove"
// String not contain escaped characters
val s2 = "Kotlin is love"
println(s1)
println(s2)
The code above outputs:
Kotlin is
love
Kotlin is love
Revise the supported escape sequences in the Characters page.
Raw strings
Raw strings contain arbitrary text and newlines, and are determined by triple quote ( “”” ). They do not contain escape characters.
Example:
val text = """
Kotlin is a modern,
and mature
programming language.
"""
println(text)
The code above outputs:
Kotlin is a modern,
and mature
programming language.
Remove whitespaces from raw strings by using trimMargin() function.
Example:
val text = """
Kotlin is a modern,
and mature
programming language.
""".trimMargin()
println(text)
To learn more about strings, visit: Kotlin Strings.