Scala: Function returning an unknown type -
if wanted make add method adds values of 2 different types like:
add[t,s](op1: t, op2: s): ? = ...
the notable example can think of basic number types. if add byte , int return int. if 2 bytes added return int depending on if -127 128 limit byte broken.
further more if wanted create classes had same characteristics same.
one possible solution have classes extend same trait or class. example of scala primitive types doesn't apply cause int, double, float, byte don't share common ancestor besides any.
i've looked @ numeric[t] trait doesn't seem when adding different primitive types.
thanks kai
this prime example kind of joint-typeclass.
start defining thing numeric[t]
, addability:
trait addable[t, s] { type result def add(x: t, y: s): result }
now, define add
function:
def add[t,s](op1: t, op2: s)(implicit op: addable[t, s]): op.result = op.add(op1, op2)
all have left, create implicit instances addable
:
// put them in companion object, implicits available // without explicit import object addable { // make numeric addable implicit def numericaddable[t : numeric]: addable[t, t] = { new addable[t, t] { type result = t def add(x: t, y: t): t = { val op = implicitly[numeric[t]] op.plus(x, y) } } } }
but can define own classes , define (assymetric) addition capability:
case class a(x: int) case class b(x: int) case class c(x: int) implicit object addabc extends addable[a,b] { type result = c def add(x: a, y: b): c = c(x.x + y.x) }
this allow write:
add(a(1), b(2))
however, of these fail @ compile time:
add(a(1), a(2)) add(b(1), a(2)) add(b(1), b(2))
unfortunately, not work weak conforming numeric types:
add(1, 1) // compiles add(1.0, 1.0) // compiles add(1, 1.0) // fails compile
judging another post, there not way achieve that, define cases manually (with helper methods of course).
Comments
Post a Comment