1

I spent all this time putting together a factory method in my companion object like so:

class Stuff(val a: Int, val b: Long) { this() = this(0,0L) }

object Stuff {
  def apply(a:Int, b:Int) = new Stuff(a, b.toLong)
}

But when just when I thought I was killing it I then went to compile and this didn't work:

val widget = new Stuff(1,2)

What is going on!? I just made this!? Help!!!

crockpotveggies
  • 12,682
  • 12
  • 70
  • 140
  • Actually, if you correctly insert the missing `def` into the `class`, `new Stuff(1, 2)` should definitely work (as should `new Stuff(1, 2L)`). – Debilski Aug 22 '12 at 08:49
  • make ctor of Stuff private with `class Stuff private(...) {...}` and no confusion any more. – kiritsuku Aug 22 '12 at 09:25
  • Interesting, I didn't know that classes could also have `apply()` factories as well. Was this added later after the companion object factories? – crockpotveggies Aug 22 '12 at 16:32

1 Answers1

7

Well young Scala coder, have no fear because the answer is simple. You are not using the factory correctly. See, this code will actually do what you want:

val widget = Stuff(1,2)
//makes Stuff(1, 2L)

The issue here is your syntax. When you call new it instantiates a new class of Stuff. But apply is really syntactic sugar for widget.apply(1,2) and there's not much else to it.

You can also learn more about the apply sugar here: How does Scala's apply() method magic work?

Keep coding young one.

Community
  • 1
  • 1
crockpotveggies
  • 12,682
  • 12
  • 70
  • 140