Skip to content

Instantly share code, notes, and snippets.

@jbgi
Last active April 25, 2017 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbgi/e8e3109518c2d602a319331bf8bb3582 to your computer and use it in GitHub Desktop.
Save jbgi/e8e3109518c2d602a319331bf8bb3582 to your computer and use it in GitHub Desktop.
How to pattern match with implicit conversion?
trait A {
def toB: B
}
object A {
def unapply(arg: A): B = arg.toB
}
sealed trait B {
def isEmpty: Boolean = false
def get: B = this
}
case class B1() extends B
case class B2() extends B
object Main {
val a: A = new A() {
override def toB: B = B2()
}
val name: String = a match {
case A(B1()) => "B1"
case A(B2()) => "B2"
}
// or, of course:
val name2: String = a.toB match {
case B1() => "B1"
case B2() => "B2"
}
}
trait A {
implicit def toB: B
}
sealed trait B
case class B1() extends B
case class B2() extends B
object Main {
implicit class AOps(a: A) {
implicit def toB: B = a.toB
}
val a: A = new A() {
override implicit def toB: B = B2()
}
// How to make the following to compile without change?
val name: String = a match {
case B1() => "B1"
case B2() => "B2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment