How can (1 +) be a function?

I am new to Scala and trying to understand the following codes (derived from an example in the Beginning Scala book)

scala> def w42(f: Int => Int) = f(42) //(A) w42: (f: Int => Int)Int scala> w42 (1 +) //(B) res120: Int = 43 

I don’t understand how β€œ1 +” at point (B) is considered as a function (take 1 parameter Int and return Int) that satisfies the definition of w42 at point (A)?

Could you explain or point me to some documents that have an answer?

+6
source share
1 answer

Simple In Scala 1 + 2 there is only syntactic sugar over 1.+(2) . This means that Int has a method called + that accepts Int :

 final class Int extends AnyVal { def +(x: Int): Int = //... //... } 

That is why you can use 1 + as if it were a function. An example with a less unexpected method name:

 scala> def s42(f: String => String) = f("42") s42: (f: String => String)String scala> s42("abc".concat) res0: String = abc42 

BTW Technically speaking, the eta extension is also used to convert a method to a function.

+11
source

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


All Articles