Skip to content

Instantly share code, notes, and snippets.

@majk-p
Last active December 16, 2022 15:42
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 majk-p/75fe4466cb9c2d315da22341175f0747 to your computer and use it in GitHub Desktop.
Save majk-p/75fe4466cb9c2d315da22341175f0747 to your computer and use it in GitHub Desktop.
Type bounds <: vs <:<
//> using scala "2.13"
sealed trait SampleTrait
case class SampleValue(v: String) extends SampleTrait
object SampleSingleton extends SampleTrait
def f[X <: SampleTrait](x: X): Unit =
println(x)
def g[X](x: X)(implicit ev: X <:< SampleTrait): Unit =
println(x)
f(SampleSingleton)
f(SampleValue("hello"))
g(SampleSingleton)
g(SampleValue("hello"))
// case class C(v: String)
// f(C("hello")) // Doesn't compile
// g(C("hello")) // Doesn't compile
trait Algebra[A] {
def op(a: A, b: A): A
}
implicit val algebraForA: Algebra[SampleTrait] = {
case (SampleValue(v1), SampleValue(v2)) => SampleValue(v1 + " " + v2)
case _ => SampleSingleton
}
implicit class Test[A](private val a: A) {
def worksForAnyType(): Unit = println("worksForAnyType")
def worksForSampleTraitSubtype(b: A)(implicit ev: A <:< SampleTrait): Unit = println(
s"worksForSampleTraitSubtype ${implicitly[Algebra[SampleTrait]].op(a, b)}"
)
}
10.worksForAnyType()
// 10.worksForSampleTraitSubtype(10) this doesn't compile
SampleValue("hello").worksForAnyType()
SampleValue("hello").worksForSampleTraitSubtype(SampleValue("world"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment