23

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.

Chris Eidhof
  • 1,514
  • 1
  • 12
  • 15

3 Answers3

21

This will work:

def mkPerson = (new Person(_, _, _)).curried
Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
  • 2
    Just a quick note, if you're sure to call it may as well make it `val mkPerson = ...`. Also, if Person were a case class you could simply use `(Person.apply _).curried` – Geoff Reedy Oct 05 '10 at 22:13
11

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.

Erik Post
  • 826
  • 7
  • 12
8

may be so:

val mkPerson = Function.curried((n: String,a:Int,e:String) => new Person (n,a,e))
walla
  • 1,087
  • 8
  • 9
  • I see. It's still more complex than I'd hoped for: I was thinking of something more along the lines of Haskell constructors. – Chris Eidhof Oct 05 '10 at 14:36