Yann Moisan
Yann Moisan

Reputation: 8281

Partially applied Function2 with first and second argument

Given a method

def f(a: String, b: String) = ???

I want to get both partially applied function (with first argument and with the second one).

I've written the following code :

def fst = f _ curried "a"
def snd = (s: String) => (f _ curried)(s)("b")

Is there a better way ?

[update] snd could be written shorter def snd = (f _ curried)((_: String))("b")

Upvotes: 3

Views: 232

Answers (2)

yǝsʞǝla
yǝsʞǝla

Reputation: 16422

Another way to do it is to use multiple parameter lists:

def f(a: String)(b: String) = ???

No args supplied:

def fst = f _

First arg supplied:

def fst = f("a")

Only second arg supplied:

def fst = f(_: String)("b")

All args supplied:

def snd = f("a")("b")

If you are currying args in the same order they are defined then this syntax is a bit cleaner than the one used in the question.

Upvotes: 2

Alexey Romanov
Alexey Romanov

Reputation: 170899

This is simpler:

def fst = f("a", (_: String))
def snd = f((_: String), "b")

But note it recalculates the partially applied functions on every call, so I'd prefer val (or maybe lazy val) instead of def in most circumstances.

Upvotes: 5

Related Questions