- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 366字
- 2021-06-24 14:13:29
Smart casts
If, after type checking, we want to refer to the variable as an instance of B, then the reference must be cast. In Java, this must be done explicitly, which results in duplication:
public void printStringLength(Object obj) { if (obj instanceof String) { String str = (String) obj System.out.print(str.length()) } }
The Kotlin compiler is more intelligent, and will remember type checks for us, implicitly casting 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) } }
The compiler knows that we can only be inside the code block if the variable was indeed an instance of string, and so the cast is performed for us, allowing us to access methods defined on the string instance.
Which variable can be used in a smart cast is restricted to those that the compiler can guarantee do not change between the time when the variable is checked and the time when it is used. This means that the var fields and local variables that have been closed over and mutated (used in an anonymous function that assigns a new value) cannot be used in smart casts.
Smart casts even 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 }
The compiler knows that, in this && expression, the right-hand side will not be evaluated unless the left-hand side was true, so the variable must be a string. The compiler, therefore, smart casts for us and allows us to access the length property on the right-hand side.
Similarly, in a || expression, we can test that a reference is not of a particular type on the left-hand side, and if it is not, then on the right-hand side it must be that type, so the compiler can smart cast the right-hand side:
fun isNotStringOrEmpty(any: Any): Boolean { return any !is String || any.length == 0 }
In this example, the function tests that we either don't have a string, or, if we do, then it must be empty.
- 微服務(wù)設(shè)計(jì)(第2版)
- Django+Vue.js商城項(xiàng)目實(shí)戰(zhàn)
- Apache ZooKeeper Essentials
- Redis Applied Design Patterns
- ASP.NET Core 2 and Vue.js
- Python爬蟲開發(fā)與項(xiàng)目實(shí)戰(zhàn)
- 算法訓(xùn)練營(yíng):提高篇(全彩版)
- 小程序開發(fā)原理與實(shí)戰(zhàn)
- 高級(jí)語言程序設(shè)計(jì)(C語言版):基于計(jì)算思維能力培養(yǎng)
- Apache Spark 2.x for Java Developers
- C++新經(jīng)典
- C++反匯編與逆向分析技術(shù)揭秘(第2版)
- 細(xì)說Python編程:從入門到科學(xué)計(jì)算
- Hands-On Neural Network Programming with C#
- Unity 2018 Augmented Reality Projects