简体   繁体   English

Scala中的类型函数和Currying

[英]Typed Function and Currying in Scala

In Scala let's say I have a function like this: 在Scala中,假设我有这样的函数:

def foo[R](x: String, y: () => R): R

so I can do: 所以我可以这样做:

val some: Int = foo("bar", { () => 13 })

Is there a way to change this to use function currying without "losing" the type of the second argument? 有没有办法改变这个使用函数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

Functions can't have type parameters, you have to use a custom class like this: 函数不能有类型参数,你必须使用这样的自定义类:

def foo(x: String) = new {
  def apply[R](y: () => R): R = y()
}

val bar = foo("bar")
val some: Int = bar(() => 13)
// Int = 13

To avoid structural typing you could create custom class explicitly: 要避免结构类型,您可以显式创建自定义类:

def foo(x: String) = new MyClass...

A variation on senia's answer, to avoid structural typing: 关于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

Not really a solution to your problem but just to point out that you can still use the second version of your function if you supply the type explicitly: 不是解决问题的方法,而是指出如果明确提供类型,仍然可以使用函数的第二个版本:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM