generics - Types in Scala - lower bounds -
on code below.
my expectation t
must of type b
or a
, call lowerbound(new d)
should not compile (?). similar experiments upperbound give me expected typecheck errors.
thanks giving hint.
object variancecheck { class { override def tostring = this.getclass.getcanonicalname } class b extends class c extends b class d extends c def lowerbound[t >: b](param: t) = { param } println(lowerbound(new d)) //> variancecheck.d }
with implementation can write:
scala> def lowerbound[t >: b](param: t) = { param } lowerbound: [t >: b](param: t)t scala> lowerbound(new anyref {}) res0: anyref = $anon$1@2eef224
where anyref
super type of object/reference types (actually alias java object
class). , right, t >: b
expresses type parameter t
or abstract type t
refer supertype of type b
.
you have bad example tostring
, cause method has object types, if change to, let's on somemethod
, lowerbound
won't compile:
<console>:18: error: value somemethod not member of type parameter t def lowerbound[t >: b](param: t) = { param.somemethod }
if change t <: b
, means parameter of type t
subclass of b
, good, cause param
has somemethod
method:
def lowerbound[t <: b](param: t) = { param.somemethod }
Comments
Post a Comment