Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interesting behaviour with infix notation

Tags:

scala

One sometimes try to get away from your girlfriend by hiding behind your computer screen. However, I find that Scala is sometimes exactly like my girl...

This prints the intersection between two lists:

  val boys = List(Person("John"), Person("Kim"), Person("Joe"), Person("Piet"), Person("Alex"))

  val girls = List(Person("Jana"), Person("Alex"), Person("Sally"), Person("Kim"))

  println("Unisex names: " + boys.intersect(girls))

This prints absolutely nothing:

  val boys = List(Person("John"), Person("Kim"), Person("Joe"), Person("Piet"), Person("Alex"))

  val girls = List(Person("Jana"), Person("Alex"), Person("Sally"), Person("Kim"))

  println("Unisex names: " + boys intersect girls)

There are no compiler warnings and the statement prints absolutely nothing to the console. Could someone please explain gently (I have a hangover), why this is so.

like image 774
Jack Avatar asked Dec 25 '22 08:12

Jack


1 Answers

It gets desugared to this:

println("Unisex names: ".+(boys).intersect(girls))

then according to the -Xprint:typer compiler option it gets rewritten like this:

println(augmentString("Unisex names: ".+(boys.toString)).intersect[Any](girls))

where augmentString is an implicit conversion from type String to StringOps, which provides the intersect method.

like image 63
Nikita Volkov Avatar answered Feb 08 '23 11:02

Nikita Volkov