I'm trying to create a function that checks if a condition applies and runs any possible expression if it does, in case the condition doesn't apply this function returns a default value, I'm able to do it in the following way:
def executeOnCondition[T](condition: Boolean, default: T)(f: => T): T = if (condition) f else default
however I'd like this function to be curried so that it first takes the condition and default and only later executes the expression. imagined use:
val useLater = executeOnCondition(true, 3.14)
// do stuff
useLater { 3.14 * 2}
but when I try to create my curried function in the expected way:
def executeOnCondition[T](condition: Boolean, default: T) = (f: => T) => { if (condition) f else default }
I get this compilation error:
identifier expected but '=>' found.
I guess the problem is related to the use of generics, can anyone shed some light and maybe offer a work-around?
many thanks
CodePudding user response:
This is the proper syntax:
def executeOnCondition[T](condition: Boolean, default: T): (=> T) => T =
block => if (condition) block else default
For some reason (bug?) you can't type => T
as the type of a lambda input, even though the type is valid.