2

I am trying to pass a function as a parameter, but that function has multiple arguments (one of which is a function).

Here is what I am trying to do in a basic Python example:

def first(string1, string2, func): func(string1, string2, third) def second(string1, string2, func): func(string1, string2) def third(string1, string): # operations go here first("one", "two", second) 

My attempt at this in Scala was the following:

def first(string1: String, string2: String, func: (Any, Any, Any) => Unit) = { func(string1, string2, func) } def second(string1: String, string2: String, func: (Any, Any) => Unit) = { func(string1, string2) } def third(string1: String, string2: String) = { // operations } def main(args: Array[String]): Unit = { first("one", "two", second) } 

I get an error for trying to pass second into first with an insufficient amount of arguments. Is it possible to achieve this functionality in the same style as the Python example?

EDIT:

I tried replacing the body of my main method with first("one", "two", second _) and it gives me a type mismatch error

type mismatch; found : (String, String, (Any, Any, Any) => Unit) => Unit required: (Any, Any, Any) => Unit

Any idea what's going on here?

1 Answer 1

2

What you are trying to do is not type-safe. You cannot assign (String, String, (Any, Any) => Unit) => Unit to (Any, Any, Any) => Unit. If you could, then you could do the following:

val f = second _ val af: (Any, Any, Any) => Unit = f af(1, "abc", 5) 

You can do it if you specify the types more precisely:

def second(string1: String, string2: String, func: (String, String) => Unit) = { func(string1, string2) } def third(string1: String, string2: String) = { // operations } def first(string1: String, string2: String, func: (String, String, (String, String) => Unit) => Unit) = { func(string1, string2, third) } 
Sign up to request clarification or add additional context in comments.

4 Comments

So the actual program I'd be doing has 7 functions that take another function as a parameter, all of them nested in the style of my example code. I'm guessing maintaining the style of the Python program isn't really practical with Scala?
@kevin - Yes, passing nested callbacks will get ugly quite quickly. If you're trying to do some async operations you could look at futures. Otherwise for comprehensions and macros can be used to flatten the syntactic structure of your code.
I went ahead and accepted your answer since it did solve my problem. Is there any example you could point me to in order to use macros to help?
@kevin - The Scala implementation of async/await is a pretty good example, see docs.scala-lang.org/sips/pending/async.html

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.