Set default value for function parameter in scala

Like any other default parameter:

scala> def test(f: Int => Int = _ + 1) = f
test: (f: Int => Int)Int => Int

scala> test()(1)
res3: Int = 2

or with String:

scala> def test(f: String => String = identity) = f
test: (f: String => String)String => String

scala> test()
res1: String => String = <function1>

scala> test()("Hello")
res2: String = Hello

Edit:

In case if you want to use a function provided by default, you have to use () explicitly, either Scala won't paste a default argument.

If you don't wanna use a default function and provide an explicit one, just provide it yourself:

scala> test(_.toUpperCase)("Hello")
res2: String = HELLO

Use an implicit parameter. Place an implicit value for the parameter in the object. This will be used unless you provide an explicit parameter or you have provided another implicit value in the calling scope.

case class A(id:Int = 0)

case class B(a:A)

object B {
  implicit val defFunc: A => B = {a: A =>  new B(a) }
  def func1(f:Int = 0)={
  }
  def func2(implicit func: A => B) = { ... }
} 

The differences between this method and Alexlv's method are

  1. This works with standalone functions as well as methods.
  2. The scope rules allow for providing appropriate overrides in appropriate scopes. Alex's method would require subclassing or eta-expansion (with partial application) to change the default.

I offer this solution since you are already using an object. Otherwise, Alexvlv's example is simpler.

Tags:

Lambda

Scala