0
1

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.

ExperimentalContracts メモ

Posted at

ある関数の戻り値が true だったら、その引数となった値が non-null として smart cast される例。

import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract

fun f(s: String?) {
    if (isValidString(s)) {
        // isValidString(s) implies s is not null.
        val validString: String = s // <- smart casted here!
    }
}

// checks if s starts with "hoge:".
@OptIn(ExperimentalContracts::class)
fun isValidString(s: String?): Boolean {
    contract {
        returns(true) implies (s != null)
    }
    return s?.startsWith("hoge:") == true
}
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?