开发者

scala create val for outer scope

开发者 https://www.devze.com 2023-04-05 04:10 出处:网络
Consider following object, object A { def setX(x:Int) = { val x1 = x } def getx() = x1 } If I create val x1 inside setX that\'s scope will be the method setX. what I really want to do is create a

Consider following object,

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

        def getx() = x1
    }

If I create val x1 inside setX that's scope will be the method setX. what I really want to do is create a val outside the me开发者_开发知识库thod and assign the value inside the method. Is it impossible without using var, or is there any way to do it?

Please send me an example if you can.


That is sort of the difference between val ("readonly") and var.

So no: not possible.

If the problem (not the desired solution) is explained more, there might be alternative approaches.

Happy coding.


Its hard to tell, what you actually want to achieve, but often converting your setX method does the trick:

   def setX(x:Int) = {
       x
   }

   val x1 = setX(x)

or you could create a SetOnce class which holds a value and allows to set it exactly once ...

0

精彩评论

暂无评论...
验证码 换一张
取 消