Back to questions
JuniorTheoryCommon
What happens when you build and run this program?
fun main() {
val name: String? = "Kotlin"
println(name.length)
}It does not compile: name has the type String?
- Expecting
6: thinking the compiler sees thatnameholds text. It checks only the typeString?, and a call on it needs?.or!!. - Expecting a
NullPointerExceptionat run time: the compiler stops the build first, so the program never starts and prints nothing.
- How would you print the length of
nameso that the program compiles? - What changes if
nameis declared asStringinstead ofString??