Last active
April 25, 2017 14:14
-
-
Save jbgi/e8e3109518c2d602a319331bf8bb3582 to your computer and use it in GitHub Desktop.
How to pattern match with implicit conversion?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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