Method signature for a function with default values

In Scala, is there a way to specify that a function should have default parameter values declared?

For example, in the code below, is there a way to specify in the signature of indirectHelloName that the provided function must provide a default value for the second parameter?

def helloName(name: String, greating: String = "hello"): Unit = { 
  println(s"$greating $name")
}

def indirectHelloName(name: String, function: (String,String) => Unit): Unit = {
  if (name == "Ted") {  
    function(name, "Custom Greeting for Ted!")
  } else {
    function(name) //This would use the default value for the second argument.
  }
}

2 answers

  • answered 2018-11-07 22:20 Rajkumar Natarajan

    I tried and come up with the below answer

        def helloName(name: String, greeting: String = "hello"): Unit = {
            println(s"$greeting $name")
        }
    
        val helloNameFn = (x: String, y :String) =>  println(x + y)
    
        type fn = (String, String) => Unit
    
        def indirectHelloName(name: String, function:fn = helloNameFn): Unit = {
            if (name == "Ted") {
            function(name, "Custom Greeting for Ted!")
            } else {
            helloName(name) //This would use the default value for the second argument.
            }
        }
    
        helloNameFn("123", "123")
    

    Please try and let me know your comments.

  • answered 2018-11-07 22:39 jwvh

    One thing you could do is move the default value from the parameter list to inside the method.

    def helloName(in :String*) :Unit =
      println(in.lift(1).getOrElse("hello") + ", " + in.head)
    
    def indirectHelloName(name: String, function: (String*) => Unit): Unit =
      if (name == "Ted") function(name, "Custom Greeting")
      else               function(name) //use default
    

    usage:

    indirectHelloName("Ted", helloName)  //Custom Greeting, Ted
    indirectHelloName("Tam", helloName)  //hello, Tam