0

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

2 Answers 2

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks :) This is the approach I went for.
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.