scala> List((1, 9), (2, 3), (5, 89)).toMapres1: scala.collection.immutable.Map[Int,Int] = Map(1 -> 9, 2 -> 3, 5 -> 89)
scala> List("hello", "world").toMap<console>:8: error: Cannot prove that java.lang.String <:< (T, U).List("hello", "world").toMap^
Dear members,
I am confused by the chapter 21.8 of Cay S. Horstmann book "Scala for
the Impatience" where the author writes about evidence.
I am confused about the usefulness of T=:=U , T<:<U and T<%<U . I
would be thankful if you could provide practical examples!
Best
Edmondo
I understand,
1) but if two types are the same, they are the same type, so why would
you need them to be constrained?
scala> case class Foo[A](a: A) {| def +(that: Foo[Int])(implicit ev: A =:= Int) = Foo(this.a + that.a)| override def toString = a.toString| }defined class Fooscala> val a, b = Foo(5)a: Foo[Int] = 5b: Foo[Int] = 5scala> a + bres0: Foo[Int] = 10scala> Foo("hello") + Foo("world")<console>:10: error: type mismatch;found : java.lang.String("world")required: IntFoo("hello") + Foo("world")^scala> Foo("hello") + Foo(11)<console>:10: error: Cannot prove that java.lang.String =:= Int.Foo("hello") + Foo(11)^scala> Foo(3).toStringres3: java.lang.String = 3scala> Foo("hello").toStringres4: java.lang.String = hello
2) If T<:<:U why don't one writes myMethod[U,T<:U] and uses the evidence?
class List[+A] {/* stuff */def toMap[T, U](implicit ev: A <:< (T, U)): Map[T, U] = /* stuff *//* stuff */}
3) I can clearly see the usefulness
Best
Edmondo
2012/5/11 missingfaktor <rahul.ph...@gmail.com>:
Take a look at max, min, sum and product on Seq (well,
GenTraversableOnce actually).
Thank you....
That was the factor I was missing!
It let you implement specialized methods which you will be able to
call only for specific type constraint :D
Too good to be true :) Does it come with any performance warning or
can be used without moderation ?:)