2

The Scala Docs on object comment:

In fact, a case class with no type parameters will by default create a singleton object of the same name, with a Function* trait implemented.

What does the with a Function* trait implemented mean?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Kevin Meredith
  • 41,036
  • 63
  • 209
  • 384

1 Answers1

6

* is the cardinality of the case class; that is, the number of arguments it takes.

Putting it together:

case class Foo(a: Int, b: Long)

Represents code that looks like this:

class Foo(val a: Int, val b: Long) 

object Foo extends Function2[Int,Long,Foo] {
   def apply(a: Int, b: Long): Foo = new Foo(a,b)
}

The above code is not complete, case class creates a lot of other helper functions like pretty printing, unapply for pattern matching, structural equality tests, etc.

marios
  • 8,874
  • 3
  • 38
  • 62
  • The question did ask about the no-parameter case, though – OneCricketeer Dec 17 '16 at 03:31
  • Yea, if the case class is like `case class Foo[A,B](a: A, b: B)` then things get a bit more complicated. I believe with parameters there, they mean type parameters and not value arguments. – marios Dec 17 '16 at 03:33
  • So `case class A()` would extend `Function0[A]`? – Kevin Meredith Dec 17 '16 at 03:35
  • yes, but I think this goes beyond just 2.11. How far back is hard to say, but 2.10, 2.11, 2.12 should behave very similarly. – marios Dec 17 '16 at 03:37
  • @KevinMeredith To be accurate, it will create byte code that would have been the same as if there was an `object A extends Function0[A]` implementation in your code. – marios Dec 17 '16 at 03:42
  • 2
    Perhaps other folks are curious why case classes extend `Function` - http://stackoverflow.com/q/3049368/409976. – Kevin Meredith Dec 17 '16 at 03:53
  • 1
    There's an issue around explicit object https://issues.scala-lang.org/browse/SI-4808 and a recent issue around mixing in Serializable too. Maybe they'll rethink how companion generation works? – som-snytt Dec 17 '16 at 20:39