Characters, Strings and Booleans
A Char represents one UTF-16 code unit, a String represents immutable text, and a Boolean represents true or false. One visible character can require more than one Char.
Separate characters, text and boolean conditions in a small computation.
A loyalty code such as "P7", the letter on a cup, the question "is the café open?" — much of a program is text and yes/no answers rather than arithmetic. Kotlin has three types for these, and each has one detail worth knowing.
The rule
'c' is one Char, "text" is a String, true/false is a Boolean.
Char — a single character in single quotes.
val size: Char = 'M'
println('7'.digitToInt()) // 7 — the digit's value
println('7'.code) // 55 — its Unicode numberA Char is not a number in Kotlin: val n: Int = 'A' is an error. Special characters use escapes: '\n' (new line), '\t' (tab), '\'' (a single quote).
String — text in double quotes. Strings are immutable: every "change" makes a new string.
val code = "P7"
println(code.length) // 2
println(code[0]) // P — indexing gives a Char
println(code.lowercase()) // p7 — a new string; code is unchanged
println(code == "P7") // true — == compares contentsFor text over several lines, a raw string uses three quotes. It keeps line breaks as typed and does not process escapes. trimIndent() removes the common leading spaces:
val sign = """
Pebble Café
Open 8 to 6
""".trimIndent()Boolean — only true or false. Combine with && (and), || (or) and ! (not). && and || stop early: in a && b, if a is false, b is never evaluated.
val isOpen = true
val hasBeans = false
println(isOpen && hasBeans) // false
println(isOpen || hasBeans) // true
println(!hasBeans) // true