【问题标题】:Can I apply argument defaults when using partial functions in Scala在 Scala 中使用部分函数时,我可以应用参数默认值吗
【发布时间】:2014-04-21 21:02:37
【问题描述】:

我已经定义了两个偏函数(散列),我希望它们带有一个可选的第二个布尔参数:

def SHA1 = hash(MessageDigest.getInstance("SHA-1"))_
def MD5 = hash(MessageDigest.getInstance("MD5"))_
private def hash(algorithm:HashAlgorithm)(s:String, urlencode:Boolean = false) = {
    val form = if (urlencode) "%%%02X" else "%02X"
    (algorithm.digest(s.getBytes) map(form format _)).mkString
}

当我使用两个参数调用该函数时,它会编译,但只有一个参数会出现编译错误:

// First 3 tests are fine
val test1 = hash(MessageDigest.getInstance("SHA-1"))("foo", true)
val test2 = hash(MessageDigest.getInstance("SHA-1"))("foo")
val test3 = SHA1("foo", true)
// not enough arguments for method apply: (v1: String, v2: Boolean)String in trait Function2. Unspecified value parameter v2.
val test4 = SHA1("foo") 

我只是将它重构为使用部分函数,​​在我重构之前我可以强制哈希函数使用默认值而没有任何问题。

任何想法为什么部分函数实现无法允许默认参数?使用部分函数和柯里化在一起我做错了吗?

【问题讨论】:

    标签: scala currying partial-functions


    【解决方案1】:

    当您使用偏应用程序生成函数时,您将失去调用默认值的能力。方法是静态的,所以编译器知道去哪里查找默认值;一个函数可以被传递到不同的上下文中,因此编译器通常不会拥有应用默认参数所需的信息。

    换个角度来看,函数只知道它们有多少个参数。只有一种方法,apply,您可以将参数传递到其中;否则,您需要某种方式(可能是不同的类型)来区分,例如 Function2-that-must-take-two-parameters 和 Function2-that-c​​an-be-call-with-one-parameter-also-because -there-is-a-stored-default.

    【讨论】:

      猜你喜欢
      • 2011-10-26
      • 2017-09-18
      • 1970-01-01
      • 2011-04-18
      • 2014-04-28
      • 2023-03-16
      • 1970-01-01
      • 2015-05-19
      相关资源
      最近更新 更多