I am currently learning scala. I am reading Scala for the impatient.
1.)
Guards
Is there a difference?
for (i <- 0 to 10)if (i % 2 == 0) println(i)
for (i <- 0 to 10 if i % 2 == 0) println(i)
2.)
I always see the following symbol => but they never explain what it does.
Sometimes I think it is a cast but then it is something completely different, I hope you can clear things up.
1.) Yes, there is a difference, the first if a normal
ifstatement inside of the closure you pass to the for-comprehension. The second is an actual guard. It will actually callwithFilteron the range, before callingforeach. So the translation of the two things will look like this:To add a little more context, calling
withFilteror even justfilterinstead of using a normal if statement has some benefits. In a for comprehension, you can have nested calls to map, flatmap, filter, collect etc. so if you add guards, you can prevent a lot af calls from actually happening. For example:would call the actual closure 100 times
this will only call it 50 times, while the result stays the same.
2.)
=>separates the argument list of a function/closure from the body.This
case e: NumberFormatException => Noneis a part of a partial function. Here the=>separates the “argument”efrom the bodyNone.In a type signature like in
someFunction(i: (A) => Int)it implies thatiis of the typeFunction1[A,Int], read “function fromAtoInt“.