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 1 year has passed since last update.

[Kotlin]sealed interfaceの使い道(メモ)

Last updated at Posted at 2022-11-12

使い所

  • enumみたいに使いたいとき
  • elseを書きたくないとき
  • (他にもあるはずだけど私はわからない)

sealed interfaceとは

  • ざっくり、「interfaceを継承できる範囲に制限をかけれる」
  • interfaceの中に書いたやつ、もしくは同じファイル内のやつしか継承できない。
  • なのでwhenで条件分岐したときに"else"が要らなくなる。

例:ただのinterfaceの場合

fun eval(expr: Expr): Int =
    when (expr) {
        is Num -> expr.value
        is Sum -> eval(expr.left) + eval(expr.right)
        else -> throw IllegalArgumentException("Unknown expression")
    }

interface Expr
class Num(val value: Int) : Expr
class Sum(val left: Expr, val right: Expr) : Expr

sealed interfaceを使うと

fun eval(expr: Expr): Int =
        when (expr) {
            is Num -> expr.value
            is Sum -> eval(expr.left) + eval(expr.right)
        }

sealed interface Expr
class Num(val value: Int) : Expr
class Sum(val left: Expr, val right: Expr) : Expr

elseがなくてもいい...!

元コード

参考ページ

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