shakedzy
shakedzy

Reputation: 2893

Scala: Initialize Object with External Parameters

Assume I have a variable x which receives its value from the user at some point. Once that is done, I need to set up an Object which needs the value of x.

Naively, I'd like to write:

Object MyCoolObject(num:Double) {
  //code
}

and then somewhere in the code:

val MCO = MyCoolObject(x)

But that's not possible in Scala. So how do I do it?

Upvotes: 0

Views: 534

Answers (2)

Pavel
Pavel

Reputation: 1539

Something like this:

class MyCoolObject(num:Double) {    
}

object MyCoolObject{
    def apply(x:Double) = new MyCoolObject(x)
}

val x : Double = 56.1
val MCO = MyCoolObject(x)

You can use this article i.e. https://twitter.github.io/scala_school/basics2.html

Upvotes: 0

tuxdna
tuxdna

Reputation: 8477

This is already discussed here: Pass Parameters to Scala Object

You can also use a case class:

  case class MyCoolObject(num: Double)
  {
    //code
  }


  val n = 10 // external data
  val myCoolObject = MyCoolObject(n)

Upvotes: 1

Related Questions