官术网_书友最值得收藏!

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
主站蜘蛛池模板: 岳阳县| 垦利县| 天峨县| 辉南县| 定州市| 白河县| 甘孜| 耒阳市| 诸暨市| 涡阳县| 库车县| 慈利县| 乌拉特中旗| 成安县| 哈密市| 信阳市| 子洲县| 永修县| 焉耆| 玛多县| 陇川县| 册亨县| 阜城县| 微山县| 丰顺县| 伽师县| 临夏县| 乐亭县| 调兵山市| 六枝特区| 新河县| 永定县| 屯留县| 前郭尔| 普兰店市| 肥乡县| 三门县| 修水县| 黔东| 双桥区| 云梦县|