Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do I have to treat my methods as partially applied functions in Scala?

I noticed that when I'm working with functions that expect other functions as parameters, I can sometimes do this:

someFunction(firstParam,anotherFunction) 

But other times, the compiler is giving me an error, telling me that I should write a function like this, in order for it to treat it as a partially applied function:

someFunction(firstParam,anotherFunction _) 

For example, if I have this:

object Whatever {     def meth1(params:Array[Int]) = ...     def meth2(params:Array[Int]) = ... }  import Whatever._ val callbacks = Array(meth1 _,meth2 _) 

Why can't I have the code like the following:

val callbacks = Array(meth1,meth2) 

Under what circumstances will the compiler tell me to add _?

like image 706
Senthess Avatar asked Jul 11 '11 13:07

Senthess


People also ask

What is partially applied function in Scala?

The Partially applied functions are the functions which are not applied on all the arguments defined by the stated function i.e, while invoking a function, we can supply some of the arguments and the left arguments are supplied when required.

Why currying is useful in Scala?

Advantages of Currying Function in Scala One benefit is that Scala currying makes creating anonymous functions easier. Scala Currying also makes it easier to pass around a function as a first-class object. You can keep applying parameters when you find them.

What is currying in Scala?

Currying is the process of converting a function with multiple arguments into a sequence of functions that take one argument. Each function returns another function that consumes the following argument.

What is the syntax of defining method in Scala?

Syntax. def functionName ([list of parameters]) : [return type] = { function body return [expr] } Here, return type could be any valid Scala data type and list of parameters will be a list of variables separated by comma and list of parameters and return type are optional.


1 Answers

The rule is actually simple: you have to write the _ whenever the compiler is not explicitly expecting a Function object.

Example in the REPL:

scala> def f(i: Int) = i     f: (i: Int)Int  scala> val g = f <console>:6: error: missing arguments for method f in object $iw; follow this method with `_' if you want to treat it as a partially applied function        val g = f                ^  scala> val g: Int => Int = f   g: (Int) => Int = <function1> 
like image 184
Jean-Philippe Pellet Avatar answered Oct 16 '22 21:10

Jean-Philippe Pellet