Sunday, February 8, 2015

Pitfalls for Scala beginners --- Part 2

Functions vs. methods. A method m can be converted to a function using m _. Note that one can't convert the other way around. The two practical differences between functions and methods are 1) Functions cannot be generic. 2) You cannot return from a function. For example,
def foo = {
  val f = () => { return }
  f()
  println("hello") // never printed
}
Also, when you use this inside a function body, it refers to the closure where the function literal is evaluated, while this inside a method body refers to the closure where the method is defined.

No comments:

Post a Comment