Last active
August 29, 2015 13:58
-
-
Save igstan/9977913 to your computer and use it in GitHub Desktop.
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 Fn[A] { | |
def apply[B >: A](t: B): B | |
} | |
class Sup | |
class Sub extends Sup | |
def test[S >: Sub](a: Sub): Fn[S] = | |
new Fn[S] { | |
override def apply[B >: S](b: B): B = if (true) a else b | |
} | |
test(new Sub)(new Sub) // res21: scratch.Sub = scratch$Sub@6c994838 | |
// /\ | |
// || | |
// \/ | |
test(new Sub)(new Sup) // res22: scratch.Sup = scratch$Sub@450fcee3 |
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
class Sup | |
class Sub(val element: Int) extends Sup | |
def test1[B >: Sub](a: Sub, b: B): B = if (a.element < 0) b else a | |
// || | |
// || difference | |
// || | |
// \/ | |
def test2[B >: Sub](a: Sub)(b: B): B = if (a.element < 0) b else a | |
test1(new Sub(1), new Sub(1)) // res17: Sub = Sub@37e5f771 | |
test2(new Sub(1))(new Sub(1)) // res18: Sub = Sub@37900029 | |
test1(new Sub(1), new Sup) // res19: Sup = Sub@2fa357c9 | |
test2(new Sub(1))(new Sup) // WTF?! | |
// <console>:11: error: type mismatch; | |
// found : Sup | |
// required: Sub | |
// test2(new Sub(1))(new Sup) |
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 Fn[A,B] { | |
// AA is contravariant; BB is covariant | |
// Similar to Function1[-AA, +BB] | |
def apply[AA >: A, BB <: B](t: AA): BB | |
} | |
class Sup | |
class Sub extends Sup | |
def test[S >: Sub](a: Sub): Fn[S,S] = | |
new Fn[S,S] { | |
override def apply[AA >: S, BB <: S](b: AA): BB = if (true) a else b | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment