scala - Method return type covariance -
how can define method returns list[+anyref]? tried:
def a[t <: anyref](): list[t] = list[anyref]()
but reason not compile.
edit: according wong should use
def a[t <: anyref](): list[t] = list[t]()
but there way able return subtype of anyref, example
def a[t <: anyref](): list[t] = if (value) list[t]() else list[option[string]]()
here option[string] descendant of anyref, compiler not accept it
so main question if can declare method covariant return type list[+anyref]
let's make couple observations , experiment few ways of letting compiler decide on return type:
1) notice statement if (value) list[t]() else list[option[string]]()
returns 2 different specific types if
statement must return same type , else clauses. when statement returns value, compiler need infer general type 2 clauses bring in consistent constraint.
2) notice type variable t
dependent on exact type pass in when call a()
, example a[scala.io.source]()
. in method declaration gave t
upper bound t <: anyref
, means compiler has find general type union of type subtype of anyref , option[string].
3) notice return type inferred compiler removing return type declaration. i.e. def a[t <: anyref]() = if (true) list[t]() else list[option[t]]()
. compiler gave a()
return type list[anyref]
. sort of make sense because possibility general type between t
subtype of anyref
, option[of t]
.
4) try def a[t <: anyref]() = if (true) list[t]() else list[option[string]]()
. return type inferred list[java.lang.object]
. reason string
class in scala 2.8 java.lang.string
, according best guess, general type has escape scala.*
hierarchy , end in java.lang.object
unknown reasons.
5) since anyref
alias of java.lang.object
, can def a[t <: anyref](): list[anyref] = if (true) list[t]() else list[option[string]]()
force return type of list[anyref]
.
if want return subtype of anyref, have this:
def a(): list[anyref] = ...
which returns super class, , have cast returned list[anyref]
down using .asinstanceof[t]
. alternatively:
def a[t <: anyref](): list[t] = list[t]()
will gives specific type t, can't return 2 different types in if
statement in example, 1 may more specific , other, , expect return more specific type supplied when call method. because compiler has no way guarantee type in if
statement list[t] doing type checking. did make clearer?
Comments
Post a Comment