LoginSignup
2
0

More than 5 years have passed since last update.

KotlinのGeneric型としてNotNullな型を宣言する

Last updated at Posted at 2015-11-09

Kotlinで

fun <T> nullable(): T?{
  return "something" as? T
}

などと実装すると、
'T'has a nullable upper bound. This means that a value of this type may be null. Using 'T?' is likely to mislead the readerというwarningが出てきます。つまり、この型パラメータのTはすでにnullableな型の制約上にあるので、T?という書き方は読み手に誤解を与えるよ、ということです。

従ってこのTをそもそもNotNullな型として指定するには

fun <T:Any> nullable(): T? {
  return "something" as? T
}

というようにNotNullなAny型を制約としてつけてあげる必要があります。

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