Kotlin - Statement Smart casts

Introduction

The Kotlin compiler will remember type checks.

It will cast the reference to the more specific type.

This is referred to as a smart cast:


fun printStringLength(any: Any) { 
      if (any is String) { 
            println(any.length) 
      } 
} 

Smart casts work on the right hand side of lazily evaluated Boolean operations if the left-hand side is a type check:

fun isEmptyString(any: Any): Boolean { 
      return any is String && any.length == 0 
}
fun isNotStringOrEmpty(any: Any): Boolean { 
      return any !is String || any.length == 0 
} 

Related Topic