Functions · 14 of 42

Anonymous Functions 2

  • The first example is a method definition as we’ve seen before
  • The second, is like the previous slide, only assigned to a val, this is very, very roughly like the difference between

    function foo(x, y) {
        return x + y;
    }
    

    and

    var foo = function(x, y) {
        return x + y;
    }
    

    in JavaScript.

  • The third, was briefly demonstrated in the previous slide, uses the shorter _ placeholder syntax. However the usage on the left is rare in Scala, the _ notation for anonymous functions is mostly useful when passing them as parameter to higher order functions (functions that receive or return other functions)
def add1(x:Int, y:Int) = x + y //method
val add2 = (x:Int, y:Int) => x + y //anonymous function
val add3:(Int,Int)=>Int = _ + _ //alternate way
val add4 = (_ + _):((Int,Int)=>Int) //alternate way, rare

println(add1(42,13))
println(add2(42,13))
println(add3(42,13))
println(add4(42,13))

Contents

Scala basics

  1. Overview
  2. Scalculator
  3. Operators are methods
  4. Variables
  5. Final variables
  6. Printing values
  7. String interpolation
  8. String formatting
  9. Useful operations
  10. Method definition
  11. Method definition 2
  12. Method definition 3
  13. Anonymous functions
  14. Anonymous functions 2
  15. Return multiple values
  16. Declare multiple variables
  17. Assign multiple variables
  18. Loops using while
  19. Loops using for
  20. Loops without loops
  21. If
  22. Match as a switch
  23. Arrays
  24. Lists
  25. Sets
  26. Maps
  27. Mutable collections
  28. Collections: accessing elements
  29. Collections: concatenation
  30. Mutable collection operations
  31. Immutable collections with var
  32. Collections: useful methods
  33. Classes
  34. Classes, continued

What's new in Scala 3

  1. Scala 3: what changed
  2. Optional braces & new control syntax
  3. Top-level definitions & @main
  4. Enums & ADTs
  5. Extension methods
  6. given & using
  7. Union & intersection types
  8. Smaller niceties