Bruno
Bruno

Reputation: 250

Call Scala function with explicit default arguments

Is there a way in Scala to explicity tell a function that you want to use the default arguments?

Example

def myFunction(default : Int = 0) { /* logic */ }

myFunction(number match {
    case 5 => 5
    case _ => ???
 })

Is it possible to replace ??? with something that will act as calling the function with the default? (Of course, I could replace with 0, but assume this example for simplicity)

Thanks

Upvotes: 0

Views: 70

Answers (2)

Jasper-M
Jasper-M

Reputation: 15086

The right way is what @chengpohi suggests. The only way to do exactly what you asked is to mess with how scalac implements default arguments under the hood:

myFunction(number match {
  case 5 => 5
  case _ => myFunction$default$1
})

But that is very much not recommended.

Also mind that this will probably not work when pasted without adaptation in the REPL, because the REPL wraps things in additional objects and you'll have to know the absolute path to myFunction$default$1. To test it in the REPL you'll have to wrap it in an object or class:

scala> object Foo {
     |   def myFunction(a: Int = 0) = println(a)
     | 
     |   val number = 42
     |   myFunction(number match {
     |     case 5 => 5
     |     case _ => myFunction$default$1
     |   })
     | }
defined object Foo

scala> Foo
0
res5: Foo.type = Foo$@2035f1f0

Upvotes: 3

chengpohi
chengpohi

Reputation: 14217

 number match {
    case 5 => myFunction(5)
    case _ => myFunction()
 }

I think You can do it by using pattern match with function call.

Upvotes: 3

Related Questions