It is possible to define a property, that is nullable regardless of the nullability of the generic:
interface Dut<T> {
val field: T?
}
I would like to have a field the other way round, but I can not define the generic self as not nullable, as field may or may not be nullable:
interface Dut<T> {
val field: T // may be nullable or not
val listWithoutNulls: List<T!> // the exclamation mark is actually not working, but how may I define this?
}
You can define a base generic type as non-nullable:
interface Dut<T : Any> {
val field1: T // will always be non-null
val field2: T? // can be null
val field3: List<T> // list of non-nulls
val field4: List<T?> // list of potential nulls
}
You are a little wrong here. The line val dut2: Dut<String?> won’t even compile if you put the type constraint I showed <T : Any> means that a type can’t even be declared as nullable.
interface Foo<T> {
val couldBeNullableOrNot: T
val nullableAlways: T? // Totally fine even if T is already nullable.
}
interface Bar<T> {
val couldBeNullableOrNot: T
val neverNull: T!! // ERROR How does one specify non-nullable
}
interface Bizz<T> {
val couldBeNullableOrNot: T
fun <B> neverNull(): B where
B : T,
B : Any // ERROR Can't use multiple bounds when bounded by another type param
}
fun main() { println("noop") }
interface Dut<T : E?, E : Any> {
val field: T
val listWithoutNulls: List<E>
}
E must be non-nullable, but T can be either nullable or not depending on call-site. You can either use type inference or you must specify both types at once, eg:
Thanks a lot, that seems to do the trick. It may be nullable and both types have to be exactly the same.
I don’t like it very much, as I always have to specify both types, but it is a workaround. If anyone has a solution with a single generic I would be fully satisfied
funny thing here is that the notation for the type already exists, but it cannot be specified explicitly, it exists just to present type information to the reader:
It’s marked as duplicate of another request (that is not exactly the same, but the feature is included in the discussion - so good enough), that seems to be merged.