0

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?

2
  • I think you will need to dig around companion object and apply method. Commented Mar 21, 2016 at 9:04
  • It looks like everyone here is pretty confused about this question - maybe you should back up a bit and explain at a higher lever what you're trying to accomplish, and give some additional context? Otherwise I think the answer to the exact question you've presented so far is simply that it isn't possible to parameterize an object. Commented Mar 21, 2016 at 9:52

2 Answers 2

1

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

2 Comments

Thanks, but not what I'm looking for - I need to keep it as an object and not a class. also, the MongoDB way to do so is not what I have here. It's really is about passing a parameter, like n in your example
You have some misunderstanding of how Scala objects are created. Please read the duplicate question link I shared.
0

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

5 Comments

How do I call it? val MCO = Bar(x)? Will MCO hold the object or the class?
Just amended answer with proper code for you need. MCO will hold new instance of the class.
Is there any way to this with MCO still being an object and not an instance of a class?
Well, I would say yes. Not sure why you need this. But I would do something like: object MyCoolObject{ var myValue : Double = 0 def apply(x: Double) = { myValue = x this } }
You will store you value in the companion object. Try do println ( MCO.myValue) .

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.