How to define val inside constructor class in Scala

I am trying to define val inside the constructor of a class, but I am not making it work. This is a pretty intensive calculation, so I don't want to run it twice. I saw this in the following link, but when I try to do this with this code, it does not work (I still do not get the "application does not accept parameters"): How do you define the local var / val variable in the main constructor in Scala?

class MyModel( val foo: String, val bar: String, val baz: String, ) extends db.BaseModel { def this() = this( foo = "", bar = "", baz = "" ) def this( foo: SomeModel, bar: String, baz: String, ) = { this( someModel.id, doSomeComplexComputation(), doSomeComplexComputation(), ) } 

I would like to have something like:

 class MyModel( val foo: String, val bar: String, val baz: String, ) extends db.BaseModel { def this() = this( foo = "", bar = "", baz = "" ) def this( foo: SomeModel, bar: String, baz: String, ) = { val complexCalcSaved = doSomeComplexComputation() this( someModel.id, complexCalcSaved, complexCalcSaved, ) } 

But, as I mentioned above, I get "the application does not accept parameters." How should I do it?

+1
scala
Sep 27 '17 at 19:30
source share
2 answers

I would recommend creating constructors in a companion object. In your case, such an implementation may work:

 class MyModel(val foo: String, val bar: String, val baz: String) extends db.BaseModel object MyModel { //empty constructor def apply(): MyModel = new MyModel("", "", "") //another constructor def apply(foo: SomeModel, bar: String, baz: String): MyModel = new MyModel(foo.id, doSomeComputation(bar), doSomeComputation(baz)) } 

Now you can call the constructors:

 //create a MyModel object with empty constructor MyModel() //create a MyModel object with the second constructor MyModel(someModel, "string1", "string2") 
+3
Sep 27 '17 at 19:47
source share

I would write this using the companion object and the apply method:

  class MyModel( val foo: String, val bar: String, val baz: String, ) extends db.BaseModel object MyModel { def apply(): MyModel = new MyModel("", "", "") def apply(foo: SomeModel, bar: String, baz: String): MyModel = { val complexCalcSaved = doSomeComplexComputation() new MyModel(someModel.id, complexCalcSaved, complexCalcSaved) } } 
+1
Sep 27 '17 at 19:44
source share



All Articles