[英]Typed Function and Currying in Scala
在Scala中,假設我有這樣的函數:
def foo[R](x: String, y: () => R): R
所以我可以這樣做:
val some: Int = foo("bar", { () => 13 })
有沒有辦法改變這個使用函數currying而不“丟失”第二個參數的類型?
def foo[R](x: String)(y: () => R): R
val bar = foo("bar") <-- this is now of type (() => Nothing)
val some: Int = bar(() => 13) <-- doesn't work
函數不能有類型參數,你必須使用這樣的自定義類:
def foo(x: String) = new {
def apply[R](y: () => R): R = y()
}
val bar = foo("bar")
val some: Int = bar(() => 13)
// Int = 13
要避免結構類型,您可以顯式創建自定義類:
def foo(x: String) = new MyClass...
關於senia答案的一個變體,以避免結構類型:
case class foo(x: String) extends AnyVal {
def apply[R](y: () => R): R = y()
}
val bar = foo("bar")
val some: Int = bar(() => 13)
// Int = 13
不是解決問題的方法,而是指出如果明確提供類型,仍然可以使用函數的第二個版本:
scala> def foo[R](x: String)(y: () => R): R = y()
foo: [R](x: String)(y: () => R)R
scala> val bar = foo[Int]("bar") _
bar: (() => Int) => Int = <function1>
scala> bar(() => 12)
res1: Int = 12
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.