Characters, Strings and Booleans
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) // trueThe shortcut
Look at the quotes: single → Char, double → String. Then remember that indexing a String gives a Char, so code[1] == '7' is right and code[1] == "7" compares a Char with a String and does not compile.
Check the length
code.length == 2istrue.
Drills
Answer fast — trust the rule.
What is the type of "A"?
val code = "P7". What is code[1]?
What does '7'.digitToInt() return?
val s = "latte"; s.uppercase(). What is s afterwards?
In isOpen && checkStock(), when is checkStock() not called?
Remember
- Single quotes make a Char, double quotes a String; indexing a String gives a Char.
- Strings are immutable and
==compares their contents. &&and||stop early once the answer is known.
