Scala中的第一个默认参数

Scala中的第一个默认参数,scala,default,Scala,Default,有没有其他方法可以让这一切顺利进行 def b(first:String="hello",second:String) = println("first:"+first+" second:"+second) b(second="geo") 如果我仅使用以下命令调用该方法: b("geo") 我得到: <console>:7: error: not enough arguments for method b: (first: String,second: String)Unit.

有没有其他方法可以让这一切顺利进行

def b(first:String="hello",second:String) = println("first:"+first+" second:"+second)

b(second="geo")
如果我仅使用以下命令调用该方法:

b("geo")
我得到:

<console>:7: error: not enough arguments for method b: (first: String,second: String)Unit.
Unspecified value parameter second.
       b("geo")
:7:错误:方法b:(第一个:字符串,第二个:字符串)单元的参数不足。
第二个参数未指定值。
b(“geo”)

以下是一种可能的方法:您可以使用多个参数列表和咖喱:

scala> def b(first:String="hello")(second:String) = println("first:"+first+" second:"+second)
b: (first: String)(second: String)Unit

scala> b()("Scala")
first:hello second:Scala

scala> val c = b() _
c: (String) => Unit = <function1>

scala> c("Scala")
first:hello second:Scala
scala>def b(first:String=“hello”)(second:String)=println(“first:+first+”second:+second”)
(第一:弦)(第二:弦)单位
scala>b()(“scala”)
第一:你好第二:斯卡拉
scala>val c=b()_
c:(字符串)=>单位=
scala>c(“scala”)
第一:你好第二:斯卡拉

对于编译器来说,提供单个字符串参数(不命名)太不明确。可能您指的是非默认参数的值,但是。。。也许不是。因此,编译器希望您更加具体


通常,您会将所有默认参数放在方法签名的末尾(如果在本例中是这样的话,
b(“geo”)
),这样就可以不太含糊地忽略它们。

请参见scala语言规范6.6.1(http://www.scala-lang.org/docu/files/ScalaReference.pdf):

“命名参数构成参数列表e1,…,em的一个函数,即命名参数后面没有位置参数。”

def b(second:String)=b(“hello”,second)