Scala:柯里化构造函数

发布于 2024-09-26 11:35:24 字数 344 浏览 0 评论 0原文

我有以下 Scala 类:

class Person(var name : String, var age : Int, var email : String)

我想使用 Person 构造函数作为柯里化函数:

def mkPerson = (n : String) => (a : Int) => (e : String) => new Person(n,a,e)

这可行,但是还有其他方法可以实现此目的吗?这种方法似乎有点乏味且容易出错。我可以想象像 Function.curried 这样的东西,但是对于构造函数。

I have the following Scala class:

class Person(var name : String, var age : Int, var email : String)

I would like to use the Person constructor as a curried function:

def mkPerson = (n : String) => (a : Int) => (e : String) => new Person(n,a,e)

This works, but is there another way to accomplish this? This approach seems a bit tedious and error-prone. I could imagine something like Function.curried, but then for constructors.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

送你一个梦 2024-10-03 11:35:24

这将起作用:

def mkPerson = (new Person(_, _, _)).curried

This will work:

def mkPerson = (new Person(_, _, _)).curried
五里雾 2024-10-03 11:35:24

参加这个聚会有点晚了,但是如果您将 Person 设为案例类:

scala> case class Person(name: String, age: Int, email: String)
defined class Person

Scala 会生成一个包含 Person.apply(String, Int, String) 和其他一些内容的伴生对象为你。然后你可以这样做:

scala> Person.curried
res5: String => (Int => (String => Person)) = <function1>

这是缩写:

(Person.apply _).curried

它也适用于 var 参数。

A bit late to this party, but if you make Person a case class:

scala> case class Person(name: String, age: Int, email: String)
defined class Person

Scala generates a companion object containing Person.apply(String, Int, String) and some other stuff for you. Then you can do:

scala> Person.curried
res5: String => (Int => (String => Person)) = <function1>

Which is shorthand for:

(Person.apply _).curried

It works with var parameters too.

献世佛 2024-10-03 11:35:24

可能是这样:

val mkPerson = Function.curried((n: String,a:Int,e:String) => new Person (n,a,e))

may be so:

val mkPerson = Function.curried((n: String,a:Int,e:String) => new Person (n,a,e))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文