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!!!
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:
The issue here is your syntax. When you call
newit instantiates a new class ofStuff. Butapplyis really syntactic sugar forwidget.apply(1,2)and there’s not much else to it.You can also learn more about the
applysugar here: How does Scala's apply() method magic work?Keep coding young one.