سؤال

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")

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top