Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list.filter(!=) compiles, but doesn't work as expected

Tags:

scala

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.

like image 747
Harald Gliebe Avatar asked Dec 30 '19 16:12

Harald Gliebe


1 Answers

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.

like image 113
Yuval Itzchakov Avatar answered Sep 21 '22 21:09

Yuval Itzchakov