LoginSignup
1
0

More than 1 year has passed since last update.

Kotlin KoansでKotlin入門 第11回:Sealed classes

Posted at

はじめに

公式の問題集「Kotlin Koans」を解きながらKotlinを学習します。

過去記事はこちら

問題

Sealed classes

前のタスクの解決策を再利用しますが、インターフェイスをsealed interfaceに置き換えてください。そうすると、whenelse 分岐が不要になります。

修正前のコード

fun eval(expr: Expr): Int =
        when (expr) {
            is Num -> TODO()
            is Sum -> TODO()
        }

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

問題のポイント

sealed classesを使用する主な利点は、when式で使用するときに発揮されます。その文がすべてのケースをカバーしていることを確認できれば、文にelse節を追加する必要はありません。ただし、これはwhenをステートメントとしてではなく、式として(結果を使って)使用した場合のみ有効です。

fun log(e: Error) = when(e) {
    is FileReadError -> { println("Error while reading file ${e.file}") }
    is DatabaseError -> { println("Error while reading from database ${e.source}") }
    RuntimeError ->  { println("Runtime error") }
    // the `else` clause is not required because all the cases are covered
}

解答例

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