Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit conversion on traits

Given I have the following trait

trait Foo[T]{
  ...
}

I have case classes which use this trait and I would like to be able to implicitly convert Foo[T] into Foo[Z] (for example).

For instance, if I have a concrete implementation of

case class Blah[Model] extends Foo[Model]

And I have an implicit conversion of Model to View...

How do I encourage Scala to convert Blah[Model] to Blah[View] ?

trait Foo[T]{
  ...
  // not sure what to do here! 
  implicit def convertTtoZ .... (implicit converter: T=>Z) ...
}
like image 533
Chris James Avatar asked Jun 03 '26 09:06

Chris James


1 Answers

You have to explicitly define how to build the trait with an altered parameter:

scala> import language.implicitConversions

scala> class M
defined class M

scala> class N
defined class N

scala> implicit def m2n(m: M): N = new N
m2n: (m: M)N

scala> class X[A](val a: A) {}
defined class X

scala> implicit def xa2xb[A,B](x: X[A])(implicit ab: A => B) = new X(ab(x.a))
xa2xb: [A, B](x: X[A])(implicit ab: A => B)X[B]

scala> val xm = new X(new M)
xm: X[M] = X@21606a56

scala> def xnRequired(xn: X[N]) { println("Hi!") }
xnRequired: (xn: X[N])Unit

scala> xnRequired(xm)
Hi!
like image 188
Rex Kerr Avatar answered Jun 05 '26 22:06

Rex Kerr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!