1

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)
    }
}

1 Answer 1

3

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()
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, did like you suggested. Do you know how can I then retrieve o.i and o.s. The compiler tells me value i is not a member of object
@StephanRozinsky add val to class definition: class MyObj(val i: Int, val s: String)
make MyObj a case class instead of a class and you should be able to access the parameters...
@Sergey Lagutin дзякуй :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.