Scala 中的类型化函数和柯里化 [英] Typed Function and Currying in Scala

查看:42
本文介绍了Scala 中的类型化函数和柯里化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Scala 中,假设我有一个这样的函数:

In Scala let's say I have a function like this:

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

所以我可以这样做:

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?

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

推荐答案

senia 答案的变体,以避免结构化类型:

A variation on senia's answer, to avoid structural typing:

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 中的类型化函数和柯里化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆