Kotlin Basics: Large tree of condition statements - devrath/KotlinAlchemy GitHub Wiki
Consider the structure
val finalOutput = if( ... )
{
...
//returns String
}else if( ... ){
...
//returns Int
}else if( ... ){
...
//returns Double
}
- We can observe that each block returns a different datatype - > The way
kotlin
compiler resolves this is it has an Any()
type meaning return type can be any of the types.
- The way compiler does is the final result will become the data type of the tree.
Always define a type in this large nested condition
- This is because, once we define a type while defining the large nested condition, the error will be thrown.
val finalOutput : String = if( ... )
{
...
//returns String
}else if( ... ){
...
//returns Int | - > Error is thrown
}else if( ... ){
...
//returns Double | - > Error is thrown
}