Interesting behavior with infix notation

Sometimes try to get away from your girlfriend, hiding behind the screen of your computer. However, I find that Scala is sometimes just like my girlfriend ...

This displays the intersection between the 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 does 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 does not output anything to the console. Can someone please explain gently (I have a hangover) why this is so.

+4
source share
1 answer

He gets the following:

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

then, according to the -Xprint:typercompiler option , it will be overwritten as follows:

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

where augmentStringis the implicit type- Stringto- type conversion StringOpsthat the method provides intersect.

+10
source

Source: https://habr.com/ru/post/1542423/


All Articles