Question

Hopefully not a silly question - scala has a lot of syntactic sugar I'm not aware of yet. I'm trying to improve as a dev and get really readible code down so that's my intention upfront.

Is it possible to create a List that will only be declared once and place it inside a method body for clarity? I want to do this and have scala put that thing in permgen and just leave it there as it will never change. Is it possible for this to be done or do I have to declare it in a class body.

eg

def method(param: Whatever) {
  val list = List("1", "1")
}

Edit: I'm taking a wild stab that it's 'final' and I'm looking now.

Was it helpful?

Solution

Semantics require that List("1", "1") is evaluated once every time method is called, just in case the call has side-effects.

AFAIK there is no modifier that would allow you to change that behavior. If you really, really do not want to declare list in the enclosing class, you could do:

class X {
  object MethodHolder {
    val list = List("1", "1")
    def method(param: ???) = ...
  }
  import MethodHolder.method


  // rest of class
}

Note: You are not allowed to use the final keyword for function variables. In Scala, final does only prevent overriding (see answer to this post).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top