简体   繁体   中英

How to check whether generic parameter T is nullable?

提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供   中文简体   中文繁体   中英对照 版本,有任何建议请联系yoyou2525@163.com。

Given a function

inline fun <reified T> foo() {
    //... do something differently if T is nullable ...
}

how do I check whether T is nullable or not?

1 anwsers

Sounds so obvious, once you know it:

T is nullable... if null can be of type T .

eg

inline fun <reified T> isTypeNullable(): Boolean = when {
    null is T -> true
    else -> false
}

cf. https://ideone.com/Pz3ia6

(Important, here, that T is reified , otherwise it will be erased and the whole thing throws an exception)

暂无
暂无

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2022 STACKOOM.COM