Reputation: 99
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.
Upvotes: 5
Views: 42033
Reputation: 1
you can add java classes in Scala , so you can create a class and put your variables in static { } method and you can get access using private get methods .
package com.test.config
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
public class ConfigurationManager {
private static String myLink;
public static String GetMyLink()
{
return myLink;
}
static {
Config config = ConfigFactory.load();
myLink = config.getString("com.test.myLink");
}
}
Upvotes: 0
Reputation: 3692
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)
}
Upvotes: 8
Reputation: 5919
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.
Upvotes: 3