Data Types Workbook
Practice problems for In Kotlin, There Are No Primitives. Each takes a minute or two. Write your own answer first, then click Show answer — nothing here is a trick question, just direct practice of the syntax from the lesson.
val, var, and the number types
1. Read-only and mutable
Declare a read-only name holding "Ada" and a mutable age holding 36, then reassign age to 37.
Show answer Hide answer
val name = "Ada"
var age = 36
age = 37 2. Literals pick their type
Write literals for: a Long equal to 42, a Double equal to 3.14, and a Float equal to 3.14.
Show answer Hide answer
val l = 42L
val d = 3.14
val f = 3.14f 3. A readable big number
Write the literal 8100000000 as a Long with digit separators for readability.
Show answer Hide answer
val population = 8_100_000_000L 4. No implicit widening
This doesn’t compile: val l: Long = anInt. Fix it without changing anInt’s type.
Show answer Hide answer
val l: Long = anInt.toLong()Kotlin never widens numeric types silently — you convert explicitly.
Char, strings, and templates
5. A character’s code
Given val grade: Char = 'A', get its numeric code (65).
Show answer Hide answer
grade.codeChar is its own type, not a number, so you ask for the code rather than using it as one.
6. A string template
Given val age = 36, print Next year: 37 using a string template with an expression.
Show answer Hide answer
println("Next year: ${age + 1}") 7. A raw string
Write the Windows path C:\Users\ada as a string literal without escaping the backslashes.
Show answer Hide answer
val path = """C:\Users\ada""" Nullability and the special types
8. Opt into null
Declare a String that may hold null and assign it null. Then declare one that may not hold null.
Show answer Hide answer
var maybe: String? = null
val name: String = "Ada" 9. Length or zero
Given val maybe: String?, produce its length, or 0 when it’s null, in one expression.
Show answer Hide answer
maybe?.length ?: 0 10. A function that never returns
Write fail(message: String) that always throws IllegalStateException. What’s its return type?
Show answer Hide answer
fun fail(message: String): Nothing = throw IllegalStateException(message)Nothing — the type of an expression that never returns a value.
11. The void stand-in
A function prints a line and returns no meaningful value. What is its return type, and do you have to write it?
Show answer Hide answer
The return type is Unit, and you don’t write it — it’s the default when you omit the return type.
fun log(msg: String) {
println(msg)
} Back to the lesson, In Kotlin, There Are No Primitives, or on to the next one: functions.
Comments