I found the following code in the Kotlin forum and it works fine.
sealed class JsonValue<out T>(val value: T) {
class JsonString(value: String) : JsonValue<String>(value)
class JsonBoolean(value: Boolean) : JsonValue<Boolean>(value)
class JsonNumber(value: Number) : JsonValue<Number>(value)
object JsonNull : JsonValue<Nothing?>(null)
class JsonArray<V>(value: Array<V>) : JsonValue<Array<V>>(value)
class JsonObject(value: Map<String, Any?>) : JsonValue<Map<String, Any?>>(value)
override fun toString(): String = value.toString()
}
fun main() {
var pi: JsonValue<Any?>
pi = JsonValue.JsonString("pi"); println (pi)
pi = JsonValue.JsonNumber(3.14); println (pi)
pi = JsonValue.JsonNull; println (pi)
}
But I do not understand why it uses out T
.
An answer to a question about out
in general states:
out T
[...] means functions can returnT
but they can't takeT
as arguments.
in T
[...] means functions can takeT
as arguments but they can't returnT
.
If I take a look at the above code, I can see many constructors (functions), which take T
(the value
) as an argument. And I see no function which returns T
. So my inital impression was: this must be a typo, it should be in T
. But it does not even compile with in T
.
Why is it necessary to use out T
, although the type goes into the constructor?