- 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
- TypeScript Blueprints
- Vue.js 3.x從入門(mén)到精通(視頻教學(xué)版)
- Learning Elixir
- 軟件測(cè)試項(xiàng)目實(shí)戰(zhàn)之性能測(cè)試篇
- Mastering macOS Programming
- C語(yǔ)言實(shí)驗(yàn)指導(dǎo)及習(xí)題解析
- 從Excel到Python:用Python輕松處理Excel數(shù)據(jù)(第2版)
- Learning DHTMLX Suite UI
- PHP 7+MySQL 8動(dòng)態(tài)網(wǎng)站開(kāi)發(fā)從入門(mén)到精通(視頻教學(xué)版)
- Scala編程(第5版)
- Laravel Application Development Blueprints
- SSH框架企業(yè)級(jí)應(yīng)用實(shí)戰(zhàn)
- AutoCAD基礎(chǔ)教程
- Node.js應(yīng)用開(kāi)發(fā)
- Java EE實(shí)用教程