【问题标题】:Default parameters with currying带柯里化的默认参数
【发布时间】:2011-07-01 18:12:35
【问题描述】:

我可以定义一个函数为:

def print(n:Int, s:String = "blah") {}
print: (n: Int,s: String)Unit

我可以这样称呼它:

print(5) 
print(5, "testing")

如果我对上面的内容进行咖喱:

def print2(n:Int)(s:String = "blah") {} 
print2: (n: Int)(s: String)Unit

我不能用 1 个参数调用它:

print2(5)
<console>:7: error: missing arguments for method print2 in object $iw;
follow this method with `_' if you want to treat it as a partially applied function
       print2(5)

我必须提供这两个参数。有没有办法解决这个问题?

【问题讨论】:

    标签: scala parameters currying


    【解决方案1】:

    您不能使用默认参数省略 ()

    scala> def print2(n:Int)(s:String = "blah") {}
    print2: (n: Int)(s: String)Unit
    
    scala> print2(5)()
    

    虽然它适用于隐式:

    scala> case class SecondParam(s: String)
    defined class SecondParam
    
    scala> def print2(n:Int)(implicit s: SecondParam = SecondParam("blah")) {}
    print2: (n: Int)(implicit s: SecondParam)Unit
    
    scala> print2(5)
    

    【讨论】:

    • 永远记住:空参数列表与没有参数列表不同。
    猜你喜欢
    • 2019-11-18
    • 2011-08-06
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2013-06-03
    相关资源
    最近更新 更多