[Kotlin] Typecheck with 'is' keyword, 'as' keyword for assert type

val randomNumber = Random().nextInt(3)

if (randomNumber is BigDecimal) {
    result = result.add(BigDecimal(36))
}

If you use type check, then 'result' is auto casting to BigDecimal type.

 

'as' keyword

val randomNumber = Random().nextInt(3)

if (randomNumber is BigDecimal) {
    result = result.add(BigDecimal(36))
} else {
    val tempResult: String = result as String
    result = tempResult.toUpperCase()
}

 

posted @ 2020-10-26 18:36  Zhentiw  阅读(62)  评论(0编辑  收藏  举报