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

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
主站蜘蛛池模板: 溧阳市| 苍南县| 海淀区| 东明县| 平湖市| 西吉县| 富宁县| 山丹县| 东乡县| 萍乡市| 安义县| 安西县| 乌兰察布市| 晋州市| 南华县| 安国市| 聂荣县| 丽水市| 甘泉县| 靖江市| 射洪县| 合作市| 瑞金市| 贵州省| 博野县| 石狮市| 唐河县| 广宁县| 鲁甸县| 布尔津县| 阳谷县| 谷城县| 安福县| 瑞昌市| 梅河口市| 青田县| 扎赉特旗| 陈巴尔虎旗| 泗阳县| 垣曲县| 漾濞|