具有默认值的函数的方法签名

时间:2018-11-07 21:58:01

标签: scala

在Scala中,是否可以指定函数应声明默认参数值?

例如,在下面的代码中,是否可以在indirectHelloName的签名中指定所提供的函数必须为第二个参数提供默认值?

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.
  }
}

3 个答案:

答案 0 :(得分:3)

您可以做的一件事是将默认值从参数列表移到方法内部。

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

用法:

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

答案 1 :(得分:2)

  

在Scala中,是否可以指定函数应声明默认参数值?

     

例如,在下面的代码中,是否可以在indirectHelloName的签名中指定所提供的函数必须为第二个参数提供默认值?

函数不能具有带有默认参数的可选参数,因此无法指定一个参数:

val f = (a: Int, b: Int) => a + b
//⇒ f: (Int, Int) => Int = $$Lambda$1073/0x000000080070c840@6cd98a05

val g = (a: Int, b: Int = 5) => a + b
// <console>:1: error: ')' expected but '=' found.
//        val g = (a: Int, b: Int = 5) => a + b
//                                ^

val h = new Function2[Int, Int, Int] { 
  override def apply(a: Int, b: Int) = a + b
}
//⇒ h: (Int, Int) => Int = <function2>

val i = new Function2[Int, Int, Int] {
  override def apply(a: Int, b: Int = 5) = a + b
}
//⇒ i: (Int, Int) => Int{def apply$default$2: Int @scala.annotation.unchecked.uncheckedVariance} = <function2>

i(3, 5)
//⇒ res: Int = 8

i(3)
// <console>:13: error: not enough arguments for method apply: (v1: Int, v2: Int)Int in trait Function2.
// Unspecified value parameter v2.
//        h(3)
//         ^

答案 2 :(得分:0)

我尝试过并提出以下答案

    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")

请尝试让我知道您的评论。