def check( x: Int, y: Int) (z: Int) = {
x+y+z
} //> check: (x: Int, y: Int)(z: Int)Int
def curried = check _ //> curried: => (Int, Int) => Int => Int
def z = curried(0,0) //> z: => Int => Int
z(3) //> res0: Int = 3
check(1,2)(3) //> res1: Int = 6
check(1,2)(_) //> res2: Int => Int = <function1>
I have this code in Scala and what I'm trying to achieve is to call check in this way
check(1,2)
without the third parameter in order to call check in three ways
check(1,2)(3) // with three parameters
z(3) // with just one and
check(1,2) with two parameters.
How can I do this in Scala and Java? Can I declare z as an implicit in Java? Thank you in advance.
def check( x: Int, y: Int) (z: Int)
When you use the syntax sugar above to create curried functions, you have to use the _ assign the partially applied function to a value. This way you are not invoking the function, but creating a function value instead.
val z = curried(0,0) _
However, if you do not use the syntax sugar:
def check( x: Int, y: Int) = (z:Int) => x+y+z
Then you can call it the way you want it:
check(1,2) //res2: Int => Int = <function1>
z(3) // res3: Int = 6
check(1,2)(3) // res4: Int = 6
Note that you do not have to use _ to, for example, pass the result of the partially applied function as a parameter to another function.
def filter(xs: List[Int], p: Int => Boolean): List[Int] =
if (xs.isEmpty) xs
else if (p(xs.head)) xs.head :: filter(xs.tail, p)
else filter(xs.tail, p)
def modN(n: Int)(x: Int) = ((x % n) == 0)
filter(List(1,2,3,4,5), modN(2)) //res6: List[Int] = List(2, 4)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With