Scala create value for external area

Consider the following object,

object A { def setX(x:Int) = { val x1 = x } def getx() = x1 } 

If I create val x1 inside setX, then the scope will be the setX method. what I really want to do is create a val outside the method and assign a value inside the method . Is this impossible without using var, or is there any way to do this?

Send me an example if you can.

+4
source share
2 answers

This is the kind of difference between val ("readonly") and var .

So no: impossible.

If the problem (rather than the desired solution) is explained more, there may be alternative approaches.

Happy coding.

+4
source

It's hard to say what you really want to achieve, but often converting your setX method does the trick:

  def setX(x:Int) = { x } val x1 = setX(x) 

or you can create a SetOnce class that contains a value and allows you to set it exactly once ...

0
source

All Articles