3
    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.

2
  • 1
    possible duplicate of Does java support Currying? Commented Dec 20, 2014 at 22:37
  • I'm aware of this post but unfortunately didn't help me to understand how to do this. Commented Dec 21, 2014 at 3:16

1 Answer 1

2
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)
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.