Skip to content

Instantly share code, notes, and snippets.

@lucasrpb
Last active December 30, 2016 23:09
Show Gist options
  • Save lucasrpb/1bd80f142c411a7987db449e6dcdb9c0 to your computer and use it in GitHub Desktop.
Save lucasrpb/1bd80f142c411a7987db449e6dcdb9c0 to your computer and use it in GitHub Desktop.
object Main {
trait A {
val age = 18
}
trait B {
val name = "Lucas"
}
def show(o: A | B): Unit = o match {
case a: A => println(s"age ${a.age}")
case b: B => println(s"name ${b.name}")
}
def show(o: A & B): Unit = {
println(s"${o.name}, ${o.age}")
}
trait TM1
trait T0 extends TM1
trait T1 extends T0
trait T2 extends T1
trait T3 extends T2
/*
* T must be upper bound of T3 and T3 must be upper bound of T0, i.e.: concrete type C is between <T> and T3,
* with T min of T0
*/
class Box[T >: T3 <: T0] {
def put(v: T): Unit = {}
}
class SpecificBox[T] {
def put(v: T): Unit = {}
}
class Box2[T >: T3 <: T1] {
def put(v: T): Unit = {}
}
def main(args: Array[String]): Unit = {
val v : Int | String = 22
show(new B{})
show(new A with B {})
println()
// [T0, T3]
val box1 = new Box[T0]()
box1.put(new T0{})
box1.put(new T1{})
box1.put(new T2{})
box1.put(new T3{})
// [T1, T3]
val box2 = new Box[T1]()
//box2.put(new T0{})
box2.put(new T1{})
box2.put(new T2{})
box2.put(new T3{})
// [T2, T3]
val box3 = new Box[T2]()
//box3.put(new T0{})
//box3.put(new T1{})
box3.put(new T2{})
box3.put(new T3{})
// [T3, T3]
val box4 = new Box[T3]()
//box4.put(new T0{})
//box4.put(new T1{})
//box4.put(new T2{})
box4.put(new T3{})
val box5 = new SpecificBox[T1 & T3]()
//box5.put(new T2{})
box5.put(new T1 with T3{})
// Compiler error! T must be at least T0 and max T3
val box6 = new Box2[TM1]()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment