Home > Software engineering >  datatype of anonymous function vs named function in scala
datatype of anonymous function vs named function in scala

Time:07-10

I am curious to understand the datatype of anonymous function in Scala(2.13.8).

While reading Functional programming in Scala, I see below code

scala> (x:Int,y:Int)=> x<y

As per the book, the output should be like below

res3: (Int,Int)=> Boolean = <Function2>

But what I get is

val res3: (Int, Int) => Boolean = $Lambda$883/1341083542@7c871ce4

Below code also does not shows Function2 as type in result

scala> val lessThan = (x:Int,y:Int)=> x<y
val lessThan: (Int, Int) => Boolean = $Lambda$841/566447096@559e3f67

However, When I write the below code, I can see Function2 object is created

scala> val lessThan2 = new Function2[Int,Int,Boolean] {
     | def apply(a:Int, b:Int)= a<b }
val lessThan2: (Int, Int) => Boolean = <function2>

My question is why in an anonymous function, I don't see datatype as Function2(as per the book page number 24, I should have seen it

CodePudding user response:

Language defines some syntactic sugar which REPL follows:

  • instead of Tuple2(1, 2) you can just do (1, 2)
  • same for Tulple3, Tuple4, etc
  • instead of Function1[Int, String] you can use Int => String
  • same for Function2, Function3, ...

In your example there is also the thing that REPL often shows results int the form

resN: Type: value as seen by toString

Thing is, functions cannot have a reasonable toString representation, so it prints the default JVM toString: name of the class the instance address. Author of the book simply used <function2> as a placeholder for this seemingly random String which changes for every new function, because it is inconsequential.

CodePudding user response:

Just to more concretely put what @Dima already hit the nail on the head with:

This is simply a product of the toString implementation of that Lambda instance.


// Note: `(Int, Int) => Boolean` is syntactic sugar for `Function2[Int, Int, Boolean]`

// lessThan: Function2[Int, Int, Boolean]
val lessThan: (Int, Int) => Boolean = { ( x, y ) => x < y }
// $Lambda$16/0x0000000800bb3040@edf4efb

// lessThan.isInstanceOf[Function2[Int, Int, Boolean]]
lessThan.isInstanceOf[(Int, Int) => Boolean]
// True

That is to say the output looks slightly different, but the Lambda instance you created is a sub-class of Function2

  • Related