Skip to content

Instantly share code, notes, and snippets.

@umbreak
Created August 30, 2020 17:41
Show Gist options
  • Save umbreak/3ef55fbcaf64925e763dc0a2f44bcc92 to your computer and use it in GitHub Desktop.
Save umbreak/3ef55fbcaf64925e763dc0a2f44bcc92 to your computer and use it in GitHub Desktop.
CanBuild scala
// 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