2

I'm a scala beginner and need to understand the following syntax. The structure of code is

// val context = ...
// val future = Future {...} (context)

I don't understand what this means.

val context = ExecutionContext.fromExecutorService(...)

val future = Future {

  breakable {
    while (true) {
      try {
        handle(something)
      } 
      catch {
        case _: InterruptedException =>
      }
    }
  }
} (context)   // what does this syntanx mean? Future {...} (val)

what is this (context) after right curly brace???

user2761895
  • 1,431
  • 4
  • 22
  • 38
  • Look at the docs for future, it's apply method takes two parameter lists. One for the block of code to execute ans the second is an execution context. This is called currying. The apply method takes a function to execute and returns a function, the (context) is then the argument to that function which returns a future. – puhlen Feb 01 '17 at 03:21

1 Answers1

2

In Scala, you can defined a function with multiple parameter groups. The main purpose for this is to use currying.

def foo(bar: Int)(bar2: Long) = bar + bar2

Then Scala allows you to call this function in all these ways:

@ foo{1}{2}
res1: Long = 3L
@ foo{1}(2)
res2: Long = 3L
@ foo(1)(2)
res3: Long = 3L
@ foo(1){2}
res4: Long = 3L

So you can choose to use {} or (). The {}, roughly, allow for multiple expressions, whereas the () does not. Also, {} works only for single arguments, so if you have two or more, you can only use ().

@ foo(1){println("hi");2}
hi
res7: Long = 3L
@ foo(1)(println("hi");2)
SyntaxError: found ";2)", expected "," | ")" at index 20
foo(1)(println("hi");2)

Coming back to your question, Future.apply (which is what you are using above) is defined similar to foo. It takes two parameters using the curried function syntax.

Community
  • 1
  • 1
marios
  • 8,874
  • 3
  • 38
  • 62