In your case you declare the private var
can works is that you can't change it out of the class A
since it is private
, and you can't declare a function with a out variance
parameter for the modification purpose.
The different between private var
and private set
is a private
variable don't has getter/setter just generated a field in java. but private set
properties have getter/setter and the setter is private
.
The out
variance is only for the read-mode, which means you can't add anything in it. and its actually type is a subtype of T
, or ? extends T
in java.
For the write-mode of the out
variance is equivalent to Nothing
, so you can't declare the setter
/mutable variable at all. but you can reference it with an immutable property, for example:
open class A<out T>(v: T) {
//v--- immutable
val prop1: T = v
}
If you can do it, the kotin generic is a bad thing. why? by definition,out T
is a subtype of T
, but you attempt to assign a supertype instance T
to a subtype of ? extends T
, for example:
val subInt:A<Int> = A(1);
// v--- Int
subInt.prop1 = 1; // you try to assign an Int to its subtype
// ^--- prop1 is a subtype of Int
Maybe the following example will makes you more clearly why can't adding anything into a out
variance parameter.
val int: A<Int> = A(1) // ok
val number: A<Number> = int; //ok
number._prop = 1.0;
// ^
//if you can define setter/mutable variable, you try to assign a Double into a Int