Created
August 30, 2020 17:41
-
-
Save umbreak/3ef55fbcaf64925e763dc0a2f44bcc92 to your computer and use it in GitHub Desktop.
CanBuild scala
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
// An example of building a Concrete class with implicitly available CanBuild | |
sealed trait Top { | |
type ActualType | |
} | |
trait CanBuild[A <: Top] { | |
def apply(v: String): A#ActualType | |
} | |
object Top { | |
final case class A(v: String) extends Top { | |
def a: A = this | |
override type ActualType = A | |
} | |
final case class B(v: String) extends Top { | |
def b: B = this | |
override type ActualType = this.type | |
} | |
implicit val aCanBuild: CanBuild[A] = (v: String) => A(v) | |
implicit val bCanBuild: CanBuild[B] = (v: String) => B(v) | |
def apply[V <: Top](value: String)(implicit builder: CanBuild[V]): V#ActualType = | |
builder(value) | |
apply[A]("aaa").a | |
apply[B]("aaa").b | |
apply[B]("aaa").a // doesn't compile | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment