mardi 16 février 2016

Structural Type doesn't call correct implementation?

I was under the impression that Structural Types use reflection under the hood (indicated by the need to tell the compiler to enable "-language:reflectiveCalls") and that whatever object matches the type will be using it's own version of the function. For example, if I call .contains on a Seq than it will use the Seq version, if I call it on a String then it will use the version defined in StringOps that it gets from SeqLike

So in scala 2.10.3, why does this happen:

Welcome to Scala version 2.10.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_79).
Type in expressions to have them evaluated.
Type :help for more information.

scala> type Containable = { def contains(elem:Any):Boolean }
defined type alias Containable

scala> val myMap: Map[String, Containable] = Map("A" -> "B", "C" -> Seq("A","B"))
myMap: Map[String,Containable] = Map(A -> B, C -> List(A, B))

scala> myMap("A").contains("B")
res0: Boolean = false

scala> myMap("C").contains("B")
res1: Boolean = true

scala> "B".contains("B")
res3: Boolean = true

As you can see, a String.contains(String) returns true for itself, but not if it's called while being interpretted as a Containable type, even though that matches the defined method in the StringOps class.

I have the feeling this has to do with the implementation of == since .contains documentation says:

true if this sequence has an element that is equal (as determined by ==) to elem, false otherwise.





Aucun commentaire:

Enregistrer un commentaire