Question

Let's say I have a uncompilable (yes, I know it can't be compilled cuz of func()) code

 def withCondition(func: (Nothing) => Int): Unit = 
     if (someExtConditionIsTrue) func()

But the function I want to use with this wrapper looks like

def func(a: Int = 5) = a * 2

Is there any way I can call functions like this one inside the wrapper with it's own default parameter while I do not know what exactly that function was and what was it's default parameter value?

P.S.: I found the workaround via making a an Option or to check wherever it's null but the question still remain.

Was it helpful?

Solution

This is a legit function and it properly uses default parameter:

def func(a: Int = 5) = a * 2

The type of this function is: Int => Int.

This code does not compile:

def withCondition(func: (Nothing) => Any): Unit = 
  if (someExtConditionIsTrue) func()

because your func is expected to be passed something of type Nothing. Perhaps what you meant is to have a function that takes no args:

def withCondition(func: => Int): Unit =
  if (someExtConditionIsTrue) func()

Or you can "push" default parameter to the wrapper function:

def withCondition(func: Int => Int, a: Int = 5): Unit =
  if (someExtConditionIsTrue) func(a)

// call it:
withCondition(func)

You can try implicit parameters instead of default ones like this:

implicit val defaultArg = 5

and then either:

def withCondition(func: Int => Int)(implicit a: Int): Unit = func(a)

or pass directly to func:

def func(implicit a: Int) = a * 2

EDIT

To call a function that has default arg you can use:

scala> def withCondition(func: => Int): Unit = println(func)
withCondition: (func: => Int)Unit

scala> def func(a: Int = 5) = a * 2
func: (a: Int)Int

scala> withCondition(func())
10

// or

scala> withCondition(func(3))
6

If you use this form: def withCondition(func: => Int) then it means that it takes a function that returns an Int and takes no args. In this case you have to provide that value for the function before you pass it to the wrapper function because wrapper function can't pass any args to a function that does not take args. In your case you achieve that either by using default arg or by explicitly passing an arg to func like in the examples above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top