I can’t really understand why this example fails, if someone can explain me please ? And advice me how to solve that please ? Try Haxe !
class Session {
public function new(){}
public function get(){
return this;
}
}
class Test<T:Session> {
var session : T;
public function new( ?s : T ){
//session = s; // OK
session = s.get(); // Session should be Test.T
}
static function main() {
var sess = new Session();
var inst = new Test( sess );
}
}
The problem is that in your program there is no guarantee that Session is assignable to Test.T, because T can be a subtype of Session.
For example consider this:
class Session2 extends Session {}
function main() {
var inst2 = new Test(new Session2());
}
In this case the field Test.session is of type Session2 but the method Session.get still returns a value of type Session, that is not assignable to Session2.
Thx for your answer but this works fine : Try Haxe !
class Session {
public function new(){}
public function get(){
return this;
}
}
class MySession extends Session{}
class Test<T:Session> {
var session : T;
public function new( ?s : T ){
session = s; // OK
//session = s.get(); // Session should be Test.T
}
static function main() {
var sess = new MySession();
var inst = new Test( sess );
}
}
Your last example works because Test.session and s are of the same type, namely T.
On the other hand the type of Test.session and the return type of Session.get are T and Session, where T is a subtype of Session. So you need a downcast.
In my last example MySession is of type extended from Session, not the same type. I would understand to do something in that case but not in the other where I return exact the same type which is expected…
I know Kevin but I think here we misunderstood, with the 2nd exampe which is not what I would to do first.
Your first reply “satisfy” my curiosity.
The 2nd example is something else.