What is function type here?


val isEven = (i: Int) => i % 2 == 0

Book(by Alvin Alexander) says isEven is a function of type Int => Boolean, and is it instance of Function1.
Does it mean isEven is of type Function1 too?

scala> val isEven = (i: Int) => i % 2 == 0
isEven: Int => Boolean = <function1>

That is from the Scala REPL. So what the second line is telling you is, "isEven takes an Int and returns a Boolean. Since this is a val, that means it is an instance of Function1. vals like this are literal functions and are backed by the FunctionN classes.

I’m a bit confused, but I think the the way to read <function1> is that <function1> is the value of isEven. The Scala REPL is just not printing out the whole function and instead shortening it to <function1>.

Of course I could be completely wrong so I’m glad to hear someone else’s input.

The type of the isEven is Function1[Int, Boolean]
Int => Boolean is a syntactic sugar for the same.

Daniel is correct that is the scala repl’s way of printing the
value of isEven, as though something like this were the case:

trait Function1[P1, R] {
def toString = “”
// …

1 Like

Int => Boolean is just shorthand for Function1[Int, Boolean]. so yes, isEven is a Function1.


Thanks for the input.
For me though REPL gives this:

scala> val isEven = (i: Int) => i % 2 == 0
isEven: Int => Boolean = $$Lambda$1016/805530136@3ccb12d

The toString on FunctionN changed between Scala 2.11 and 2.12 because 2.12 uses Java 8 lambdas to represent function values, so we get Oracle’s standard toString for lambdas ($$Lambda$...).

1 Like

In general ,is not adding syntactic sugar a bad idea? I prefer to be exposed to inner workings of a system to understand it better.

Perhaps you should try a bytecode assembler then :sweat_smile:

1 Like

liking (or disliking) syntactic sugar is merely a matter of taste and habit

I remember teaching Scala’s for loop to a new developer in the project

he did not see the nested looping in

for { x <- mx ; y <- my } yield (x, y)

when I told him it was syntactic sugar for

mx flatMap { x => my flatMap { y => result (x, y) } }

he was happy to have seen the nested looping (nested curly braces)
and could choose to ignore the desugared version (or not)

but, then again, this was just one developer

I think that all that syntactic sugar is an important part of the Scala experience. However, what I dislike is that there are so many ways to express the same thing (i.e. functions). That‘s not necessary and sometimes just confusing.

Syntactic sugar is good if it can be understood by its own logic. We can
often understand what for does without knowing what it is desugared to,
so that’s good sugar.

I fully agree, my reply above confirms that exceptions prove the rule.