The following Scala code compiles but does not do what I expected:
scala> List((1,1),(1,2)).filter(!=)
res1: List[(Int, Int)] = List((1,1), (1,2))
What does !=
refer to in above code?
I know that I can write the predicate correctly as
scala> List((1,1),(1,2)).filter { case (a, b) => a != b }
res1: List[(Int, Int)] = List((1,2))
but I'm curious what the first expression actually does.
The Scala compiler does the following expansion (you can see this yourself when running scalac with the -Xprint:typer
flag):
List.apply[(Int, Int)]
(scala.Tuple2.apply[Int, Int](1, 1), scala.Tuple2.apply[Int, Int](1, 2))
.filter(((x$1: Any) => this.!=(x$1)));
Meaning it attempts to compare this
agains't your tuple which is lifted to Any
, which is not what you're trying to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With