(´ワ`)

主に技術系備忘録、たまに日記。

Kotlinのsealedキーワードで勘違いしてはいけないこと

注意

本記事はあくまで 2023/03/13 時点の備忘録ですので内容が変更する可能性があります。 今のところは個人的な備忘録で残している内容です。

概要

現時点でも「kotlin sealed class」あるいは「kotlin sealed interface」などで調べると、上位に出てくる検索結果のsealed キーワードの仕組みとして「同一ファイル内でしか継承・実装不可」といった内容で挙げる記事があるが、これは Kotlin 1.5 が安定版になった時点で「同一パッケージ内」に変更されている。

kotlinlang.org

Sealed classes can now have subclasses in all files of the same compilation unit and the same package. Previously, all subclasses had to appear in the same file.

シールドクラスは、同じコンパイルユニットを同じパッケージのすべてのファイルでサブクラスを持つことができるようになりました。以前は、すべてのサブクラスが同じファイルに存在する必要がありました。

そのため、使用している Kotlin バージョンが 1.5 以上であれば、設定と相談した上でパッケージ内に定義しておくことも可能。

余談

Scala でも同等の機能を持てるsealed キーワードがあるが、こちらは同一ファイル内に制限されている。

docs.scala-lang.org

On the flip side, exhaustivity checking requires you to define all the subtypes of the base type in the same file as the base type (otherwise, the compiler would not know what are all the possible cases).

反対に、網羅性チェックでは、基本型と同じファイルで基本型のすべてのサブタイプを定義する必要があります (そうしないと、コンパイラは考えられるすべてのケースを認識できません)。