1

I am a newbie fascinated by Scala looking for a way of creating a method/function that takes a variable amount of functions as parameters.

Example with the * notation used in regular VarArgs

def someMethod(aNumber: Int, multipleFunctions: Int => Boolean*) = {
    var flag = true
    for (func <- multipleFunctions; if (!func(aNumber)) flag = false
    flag
}

I realize I could accept an array of functions, but if that works it just feels like there must be a way of doing it with var args.

4
  • fns: Function1[Int, Boolean]* Commented Jan 18, 2018 at 21:27
  • 1
    I'm fairly sure you can simply wrap Int => Boolean in parentheses and that would solve the problem. Commented Jan 18, 2018 at 21:29
  • @cchantep Well that was quick, thank you very much. I'm guessing you already know but this can be also written as Function[Int, Boolean], IntelliJ seems to prefer it that way. Commented Jan 18, 2018 at 21:30
  • @stefanobaghino You are correct, I should probably have thought of that, thanks! Commented Jan 18, 2018 at 21:32

1 Answer 1

1

The * token is evaluated with precedence over =>, so you can simply solve your problem by wrapping the Int => Boolean type in parentheses:

def someMethod(aNumber: Int, multipleFunctions: (Int => Boolean)*)
//                                              ^     here!    ^
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.