Question

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!!!

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top