Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a global variable in scala

Tags:

scala

Is it possible to declare a global variable in this way?

if i run this snippet, i will encounter an error

object Test {
  val value -> error on this line for declaration issue
  def run() {
    value  = ... 
  }
def main(args: Array[String]) {
    run()
  }

thanks in advance.

like image 582
user582040 Avatar asked Jul 11 '15 08:07

user582040


2 Answers

You could in theory do it using a Trait. I'm not sure this is what you need though.

It would look like this:

trait MyTestTrait {
  val value: String
}

object MyTest extends MyTestTrait {
  val value = "yo!"
  def run = println(value)
}
like image 169
mfirry Avatar answered Oct 06 '22 00:10

mfirry


No, that's not possible. You should do this:

object Test {
  val value = ...
}

Since your run() function does not take parameters, the contents of value can also be computed without it.

like image 32
Madoc Avatar answered Oct 05 '22 22:10

Madoc