Skip to content

Kotlin Basics: Large tree of condition statements

Devrath edited this page Dec 24, 2023 · 1 revision

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
}
Clone this wiki locally