SwiftのOptionalとKotlinのnull許容
public.icon
2018/9/17
2018/9
2018/09/17
#trash/kotlinまとめ #trash/Swift
似てるけど実装は全くの別物だった。
SwiftはOptional型という構造体で実装されている
実行時もOptional型として動作しているので、実行時の型チェックでOptionalかどうか判定できる。
Kotlinには特別なクラスは無くて、コンパイラレベルでnull許容性のチェックをしている
実行時には「この変数がnull許容か?」の判定はできない。またSmartCastも、型が変化するように見えるのはコード上だけで、実際のインスタンスは変化していない。コンパイラとIDEがちぇっくしてくれているだけ。
サンプルコード
code:Swift
cast(nil)
cast(1)
cast("hogehoge")
}
func cast(_ a:Any?){
print("====")
print(a) // コンパイラがワーニングを出す
print(type(of:a))
guard let a=a else { return }
print(type(of:a))
// let b = a + "hoge" コンパイラがエラーを返す
guard let a2 = a as? String else { return }
print(type(of:a2))
let b2 = a2 + "hoge"
}
実行結果:
====
nil
Optional<Any>
====
Optional(1)
Optional<Any>
Int
====
Optional("hogehoge")
Optional<Any>
String
String
code:Kotlin
smartcast(null)
smartcast(1)
smartcast("hogehoge")
}
fun smartcast(a:Any?){
println("====")
println(a)
// println(a::class.simpleName) // コンパイラがエラーになる
if( a==null){ return }
println(a::class.simpleName)
if( a !is String ){ return }
println(a::class.simpleName)
val b = a + "hoge"
}
実行結果
====
null
====
1
Int
====
hogehoge
String
String