added T is nullable support
This commit is contained in:
1 parent
c54d947f1c
commit
37d093817e
9 files changed
+171
-11
No files matched your search
@@ -109,6 +109,24 @@ Examples (T = A | B):
|
||||
B in T // true
|
||||
T is A | B // true
|
||||
|
||||
# Nullability checks for types
|
||||
|
||||
Use `is nullable` to check whether a type expression accepts `null`:
|
||||
|
||||
T is nullable
|
||||
T !is nullable
|
||||
|
||||
This works with concrete and generic types:
|
||||
|
||||
fun describe<T>(x: T): String = when (T) {
|
||||
nullable -> "nullable"
|
||||
else -> "non-null"
|
||||
}
|
||||
|
||||
Equivalent legacy form:
|
||||
|
||||
null is T
|
||||
|
||||
# Practical examples
|
||||
|
||||
fun acceptInts<T: Int>(xs: List<T>) { }
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
fun describe<T>(x: T): String = when (T) {
|
||||
nullable -> "nullable"
|
||||
else -> "non-null"
|
||||
}
|
||||
|
||||
type MaybeInt = Int?
|
||||
assert(MaybeInt is nullable)
|
||||
assert(!(Int is nullable))
|
||||
assertEquals("nullable", describe<Int?>(null))
|
||||
assertEquals("non-null", describe<Int>(1))
|
||||
@@ -502,6 +502,18 @@ Aliases expand to their underlying type expressions. See `docs/generics.md` for
|
||||
|
||||
`Null` is the class of `null`. It is a singleton type and mostly useful for type inference results.
|
||||
|
||||
For type expressions, you can check nullability directly:
|
||||
|
||||
T is nullable
|
||||
T !is nullable
|
||||
|
||||
This is especially useful in generic code and in `when` over a type parameter:
|
||||
|
||||
fun describe<T>(x: T): String = when (T) {
|
||||
nullable -> "nullable"
|
||||
else -> "non-null"
|
||||
}
|
||||
|
||||
## Type inference
|
||||
|
||||
The compiler infers types from:
|
||||
|
||||
Reference in new issue
Block a user