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

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
主站蜘蛛池模板: 衡东县| 深水埗区| 柘荣县| 綦江县| 扶沟县| 乐至县| 始兴县| 兴仁县| 株洲市| 满洲里市| 哈密市| 沙坪坝区| 龙岩市| 南开区| 哈密市| 大庆市| 福海县| 杭州市| 宁南县| 大厂| 新干县| 安新县| 汉源县| 南和县| 漳浦县| 怀化市| 同心县| 招远市| 鸡泽县| 九江县| 长岭县| 丹东市| 江门市| 新闻| 嘉黎县| 诸暨市| 深水埗区| 巴林右旗| 南部县| 乌兰浩特市| 汕头市|