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

Mik*_*der 5 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.
  }
}
Run Code Online (Sandbox Code Playgroud)

Jör*_*tag 2

\n

在 Scala 中,有没有办法指定函数应该声明默认参数值?

\n\n

例如,在下面的代码中,有没有办法在签名中指定所indirectHelloName提供的函数必须为第二个参数提供默认值?

\n
\n\n

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

\n\n
val f = (a: Int, b: Int) => a + b\n//\xe2\x87\x92 f: (Int, Int) => Int = $$Lambda$1073/0x000000080070c840@6cd98a05\n\nval g = (a: Int, b: Int = 5) => a + b\n// <console>:1: error: ')' expected but '=' found.\n//        val g = (a: Int, b: Int = 5) => a + b\n//                                ^\n\nval h = new Function2[Int, Int, Int] { \n  override def apply(a: Int, b: Int) = a + b\n}\n//\xe2\x87\x92 h: (Int, Int) => Int = <function2>\n\nval i = new Function2[Int, Int, Int] {\n  override def apply(a: Int, b: Int = 5) = a + b\n}\n//\xe2\x87\x92 i: (Int, Int) => Int{def apply$default$2: Int @scala.annotation.unchecked.uncheckedVariance} = <function2>\n\ni(3, 5)\n//\xe2\x87\x92 res: Int = 8\n\ni(3)\n// <console>:13: error: not enough arguments for method apply: (v1: Int, v2: Int)Int in trait Function2.\n// Unspecified value parameter v2.\n//        h(3)\n//         ^\n
Run Code Online (Sandbox Code Playgroud)\n

  • 是的。方法可以做很多函数不能做的事情。方法可以是通用的、具有带有默认参数的可选参数、具有多个参数列表、具有隐式参数列表、本身是隐式的以及具有重载。函数不能做这些事情。你可能会问自己,如果函数比方法差那么多,为什么我们还要有函数呢?好吧,有一件非常重要的事情可以区分函数和方法:函数是对象,而方法不是。在面向对象语言中,你所做的一切都是关于对象的,这是一件大事。 (2认同)