1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Kotlin】ダウンキャストが必要な時はいつ?

Posted at

Kotlinを勉強し始めています、継承関連の復習も兼ねて、メモ。

まずKotlinの継承についてです。以下のようなAnimalクラスがあるとします。
Kotlinではopenをつけないとサブクラスが作成できません。

open class Animal {
    open fun explain() = println("動物です")
}

次にAnimalクラスを継承したCatクラスを作成します。

class Cat : Animal() {
    override fun explain() = println("猫です")
}

これをAnimalの型の変数に代入することができます。

val cat : Animal = Cat()
cat.explain()

この場合の結果はどうなるでしょうか?
実体としてはCatクラスのため、「猫です」が表示されます。

次に以下のDogクラスを作成します。

class Dog : Animal() {
    fun bark() = println("吠える")
}

これもAnimalのサブクラスのため、Animalの型の変数に代入できます。

val dog : Animal = Dog()
dog.bark()

しかし、このコードはコンパイルエラーになります。Animalクラスはbark()を知らないためですね。
なので以下のようにダウンキャストすると、コンパイルエラーは消えます。

dog as Dog
dog.bark()

しかし、Kotlinでは、型チェックをすれば、ダウンキャストしたものとして扱ってくれる便利機能があります。

if (dog is Dog) dog.bark()

これをスマートキャストといいます。
このようにKotlinでは自動でやってくれるものが多いので、徐々に慣れていきたいと思います。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?