LoginSignup
0
0

More than 1 year has passed since last update.

Kotlin KoansでKotlin入門 第7回:Nothing type

Last updated at Posted at 2022-03-11

はじめに

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

過去記事はこちら

問題

Nothing type

failWithWrongAge関数にNothing戻り値型を指定してください。
Nothing 型を指定しないと、コンパイラは年齢が NULL である可能性を想定するため、checkAge 関数がコンパイルされません。

修正前のコードです。

import java.lang.IllegalArgumentException

fun failWithWrongAge(age: Int?)    {
    throw IllegalArgumentException("Wrong age: $age")
}

fun checkAge(age: Int?) {
    if (age == null || age !in 0..150) failWithWrongAge(age)
    println("Congrats! Next year you'll be ${age + 1}.")
}

fun main() {
    checkAge(10)
}

問題のポイント

常に例外を投げる関数の戻り値型として、Nothing型を使用することができます。
この関数を呼び出すと、コンパイラは、実行がその関数の先まで続かないという情報があるためコンパイルが通ります。

解答例

import java.lang.IllegalArgumentException

fun failWithWrongAge(age: Int?): Nothing {
    throw IllegalArgumentException("Wrong age: $age")
}

fun checkAge(age: Int?) {
    if (age == null || age !in 0..150) failWithWrongAge(age)
    println("Congrats! Next year you'll be ${age + 1}.")
}

fun main() {
    checkAge(10)
}
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