user2761895
user2761895

Reputation: 1541

Don't understand the structure (or meaning of syntax) of this Scala code

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???

Upvotes: 2

Views: 96

Answers (1)

marios
marios

Reputation: 8996

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.

Upvotes: 2

Related Questions