Wednesday, 15 August 2012

scala - Union type with upper bound -



scala - Union type with upper bound -

i next technique presented in accepted reply question does scala have "type disjunction" (union types)? in order back upwards type checking multiple-type parameter method.

the implicit "evidence"

@implicitnotfound(msg="only string, array[byte] , inputstream supported") sealed class input[t] object input{ implicit object bytearraywitness extends input[array[byte]] implicit object stringwitness extends input[string] implicit object inputstreamwitness extends input[inputstream] }

the api method

def foo[t: input](param: t) = param match { case x: string => //... case x: array[byte] => //... case x: inputstream => //... case _ => throw new unsupportedoperationexception(s"not implemented type ${param.getclass}") }

the problem

this compiles

foo("test") foo(array[byte](123.tobyte))

but not (because it's not concrete inputstream)

foo(new bytearrayinputstream("abc".getbytes("utf-8")))

i have cast exact super type create work (this compiles)

foo(new bytearrayinputstream("abc".getbytes("utf-8")).asinstanceof[inputstream])

is there way alter

implicit object inputstreamwitness extends input[inputstream]

so evidence extends inputstream? have feeling there upper bound <: notation plug in somewhere, don't know where...

or "crazy lambda calculus stuff" highest voted reply aforementioned question comes rescue?

make input contra variant in type t like: input[-t], means if super type of b, input[b] super type of input[a] (reverse "inheritance"). in case means input[inputstream] knows how handle subclasses input type inputstream (like bytearrayinputstream)

i explanation on contravariance rex kerr in this question. there many others

scala types

No comments:

Post a Comment