0
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 3 years have passed since last update.

KotlinのSealed classがファイル外からアクセスできてしまう

Last updated at Posted at 2022-08-13

はじめに

KotlinのSealed classとはなんぞやということで調べてみると、
「ファイル内ならSealedClassにアクセスが可能」という情報が出てくるものの、実際に動かしてみるとファイル外からアクセスできてしまいます。原因がよくわかからなかったので調べました。


SealedClassはAndroidDeveloperの動画の中では以下のコードで説明されています。

Result.kt
sealed class Result<out T: Any> {
    data class Success<out T: Any>(val data: T) : Result<T>()
    data class Error(val exception: Exception) : Result<Nothing>()
}

「Sealed claassは同じファイル内であれば継承可能であり、この例だとResult.kt内にあるクラスであれば継承可能。なのでSuccessとErrorはResultを継承できる」と説明されています。

「ではどこからは継承不可なのかというと、ファイル外からだと継承できません」
とのことで、以下のコードが紹介され、実際にエラーが発生している様子が紹介されています。
SealedClassはResult.kt内にあるが、InProgressはNoReslt.kt内にあるので継承できない、ということです。

NoResult.kt
object InProgress:Result<Nothing>()

SealedClassError.jpg

しかし、実際に全く同じコードを書いてみるとエラーは発生せず、問題なく継承できる。なぜか?
image.png

ちなみに「ファイル内ならSealedClassにアクセスが可能」という説明はこの動画に限ったものではなく、
多くの国内外のブログ、動画で同じように説明されています。

公式はどう書いてある?

よく分からんので公式ドキュメントを確認しました。
同じファイルではなく「同じパッケージに定義する必要がある」と書かれています。
Direct subclasses of sealed classes and interfaces must be declared in the same package.
参照元

さらに公式文章の改定履歴を確認したところ以下の修正がありました。
image.png

変更前は「サブクラスはSealed Classと同じファイル内に定義せよ」と書かれています。
All direct subclasses of a sealed class must be declared in the same file as this class itself.

変更後は「Sealed Classのコンストラクタはprotectedとprivateの2つのどちらかで定義される」となっていて、デフォルトはprotectedとなっています。
Constructors of sealed classes can have one of two visibilities: protected (by default) or private

まとめ

ドキュメントの変更履歴を見る限りでは、

以前はSealed Classのコンストラクタはデフォルトでprivateだったが、現状はデフォルトではprotectedとなっているのでファイル外でもアクセスできる。
ということっぽいです。(なんか変なこと言ってましたら、ご指摘くださいませ)

※Kotlin1.5.0から変更になったようです
https://kotlinlang.org/docs/whatsnew15.html#package-wide-sealed-class-hierarchies

0
0
2

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
0
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?