Stephan Rozinsky
Stephan Rozinsky

Reputation: 623

Scala construct objects with or without arguments

In Scala, need a class that will construct a default object based on predefined computation (below the code may not be syntactically correct, but the idea is shown) if its no-params constructor is called. And I will be able to test its methods by creating an object with this(i, s) and parameters created outside. What is the best way to do that?

class myobj(i: Int, s: String) {
    def this() = {
        val j = 7 // in reality more computation with extra vals involved
        val i = j
        val str = "abcdefg"
        val s = str.get(indexOf (i % 5))
        this(i, s)
    }
}

Upvotes: 1

Views: 288

Answers (1)

dhg
dhg

Reputation: 52701

It might be better with a static factory:

class MyObj(i: Int, s: String)

object MyObj {
  def apply() = {
    val j = 7 // in reality more computation with extra vals involved
    val i = j
    val str = "abcdefg"
    val s = ""
    new MyObj(i, s)
  }
}

Then you can just do:

val o = MyObj()

Upvotes: 3

Related Questions