Kotlin does not do anything implicitly. It does not convert numeric types without your specific instruction, nor does it set a default or initializing value without it being explicit. It is a design choice to eliminate common errors that were found in typical Java programs. It isn't clear to the compiler if you forgot to initialize it or if you meant for a default value to be used. Since it isn't clear, it is bad. And therefore likely results in bugs.
The design choices of Kotlin help eliminate bugs due to code in which the compiler cannot help determine if there is an error. It is philosophical and consistent in the language.
Kotlin requires initialization before use. For members that means by the time constructors and initializers are completed, it must have a value. lateinit
modifier on var
allows this to be ignored at compile time although at runtime the check is done when you access the variable. For local variables, any branch of code must initialize the value before access. For example:
fun stateFromAbbreviation(abbreviation: String?): String {
val state: String
if (abbreviation == null) {
state = DEFAULT_STATE
}
else {
state = stateMap.get(abbreviation) ?: throw IllegalStateException("Invalid state abbreviation $abbreviation")
}
return state
}
Here the local variable can be initialized in the if
statement assuming all branches initialize the value. But really, this code would be more idiomatic using the if
as an expression, such as:
fun stateFromAbbreviation(abbreviation: String?): String {
return if (abbreviation == null) {
DEFAULT_STATE
}
else {
stateMap.get(abbreviation) ?: throw IllegalStateException("Invalid state abbreviation $abbreviation")
}
}