- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 196字
- 2021-06-24 14:13:29
Explicit casting
To cast a reference to a type explicitly, we use the as operator. Just as in Java, this operation will throw ClassCastException if the cast cannot be performed legally:
fun length(any: Any): Int { val string = any as String return string.length }
The null value cannot be cast to a type that is not defined as nullable. So, the previous example would have thrown an exception if the value was null. To cast to a value that can be null, we simply declare the required type as nullable, as we would for a reference:
val string: String? = any as String
Remember that if a cast fails, then a ClassCastException exception will be thrown. If we want to avoid the exception, and instead have a null value if the cast fails, then we can use the safe cast operator, as ?. This operator will return the casted value if the target type is compatible; otherwise, it will return null. In the next example, string would be a successful cast, but file would be null:
val any = "/home/users"
val string: String? = any as? String
val file: File? = any as? File
- ASP.NET Core:Cloud-ready,Enterprise Web Application Development
- C++程序設計教程
- The Complete Rust Programming Reference Guide
- 演進式架構(原書第2版)
- Expert C++
- Spring 5.0 By Example
- Django開發從入門到實踐
- SQL基礎教程(視頻教學版)
- Python數據可視化之Matplotlib與Pyecharts實戰
- Mastering KnockoutJS
- Arduino家居安全系統構建實戰
- 微信小程序開發與實戰(微課版)
- 進入IT企業必讀的324個Java面試題
- TypeScript圖形渲染實戰:2D架構設計與實現
- Visual Basic語言程序設計基礎(第3版)