streetsofboston
06/17/2019, 7:12 PMclass Container<T>(val value: T)
and
class Container<T>(val value: T?)
?
(note the extra ?
after the T
)?Shawn
06/17/2019, 7:16 PMShawn
06/17/2019, 7:16 PMString?
to the first Container
class’s constructor - you would get a Container<String?>
backShawn
06/17/2019, 7:17 PMString?
to the second Container
, you’d get back a Container<String>
that just holds a nullable String
Shawn
06/17/2019, 7:19 PMContainer<T>
that can potentially hold either T
or T?
, I’d recommend being explicit about it, like so:
class Container<T : Any>(val value: T?)
Pavlo Liapota
06/17/2019, 7:19 PMContainer<String>(null)
While this will not compile for first one.streetsofboston
06/17/2019, 7:20 PMstreetsofboston
06/17/2019, 7:22 PMvalue
in Container<String?>
?
What is its type in Container<String>
?
Is there such a type as String??
🙂Pavlo Liapota
06/17/2019, 7:25 PMString?
for both.
String??
is the same as String?
.streetsofboston
06/17/2019, 7:31 PMclass Container1<out T>(val value: T)
class Container2<out T>(val value: T?)
fun main() {
val s : String? = ""
val x/*: Container1<String?>*/ = Container1(s)
val y/*: Container2<String>*/ = Container2(s)
}
But you could still explicitly type y
to a nullable one:
val y: Container2<String?> = Container2(s)
Is there any difference between the first y
and the second y
?Shawn
06/17/2019, 7:33 PMy
might break smartcastingShawn
06/17/2019, 7:34 PMShawn
06/17/2019, 7:41 PMclass Wrapper<R>(private val instance: R? = null) {
fun simpleName(): String {
return if (instance != null) instance::class.simpleName ?: "default"
else "default"
}
}
Shawn
06/17/2019, 7:41 PMShawn
06/17/2019, 7:42 PMstreetsofboston
06/17/2019, 7:45 PMclass Wrapper<R>(private val instance: R)
either…Shawn
06/17/2019, 7:48 PMR
in this case I supposestreetsofboston
06/17/2019, 7:49 PMclass Container<T>(val value: T?)
is valid Kotlin, but, please, don’t use it 🙂Shawn
06/17/2019, 7:49 PMShawn
06/17/2019, 7:50 PMShawn
06/17/2019, 7:50 PMPavlo Liapota
06/17/2019, 8:13 PMclass MyList<T>(
val list: List<T>,
val defaultValue: T? = null
) : List<T> by list {
fun getOrDefault(index: Int): T?
= list.getOrElse(index) { defaultValue }
}
So you want to allow creation of both MyList<String>
and MyList<String?>
while defaultValue
should always be nullable.Pavlo Liapota
06/17/2019, 8:17 PM