j3d
j3d

Reputation: 9734

Scala: How to Define an Argument with Default Value in Partial Functions

Given the following PartialFunction...

type MyFunc = PartialFunction[(Int, Int), String]

...

val myFunc = MyFunc {
  case (i, j) => (i + j).toString
}

...

myFunc(3, 2) // returns "5"

... is there a way to have a default value for the second argument (j)? The only way I've found so far is something like this:

type MyFunc = PartialFunction[Int, String]

...

def myFunc(j: Int = 10) = MyFunc {
  case i => (i + j).toString
}

...

myFunc()(5)  // returns "15"
myFunc(5)(2) // returns "7"

The solution above implies a different PartialFunction and a methods that takes an argument with default value... but it's not exactly what I'm looking for. Are there better alternatives?

Upvotes: 1

Views: 548

Answers (2)

Tyth
Tyth

Reputation: 1824

If I understood the question correctly, how about this one?

object WrapperFunc { 
  val f = PartialFunction[(Int, Int), String] { 
    case (i,j) => (i + j).toString 
  }
 def apply(a: Int, b: Int = 5) = f (a,b) 
}
WrapperFunc(1)
WrapperFunc(1,2)

Upvotes: 1

Martijn
Martijn

Reputation: 12102

methods can have default parameters, but functions can't.

your second def myFunc is a method (so it can have optional parameters), but you can't expand that into a function.

def mymethod(j: Int = 10) = MyFunc {
  case i => (i + j).toString
}

val asFunc = mymethod _

would lose the default parameter.

If you want to have something like this, you're going to need something like

type MyFunc = PartialFunction[(Option[Int], Int), String]

val myFunc = MyFunc {
  val mydefault = 10
  case (i, j) => (i.getOrElse(mydefault) + j).toString
}

and call it as myfunc((Some(8), 3)) or myfunc((None, 3))

Upvotes: 2

Related Questions