2
votes

I am trying to use global variable in Scala. to be accessible in the whole program .

val numMax: Int = 300 

object Foo {.. }
case class Costumer { .. }
case class Client { .. }
object main {
var lst = List[Client]
// I would like to use Client as an object .

}

I got this error :

error: missing arguments for method apply in object List; follow this method with `_' if you want to treat it as a partially applied function var lst = List[A]

How can I deal with Global Variables in Scala to be accessible in the main program . Should I use class or case class in this case ?

2
With your code comment, it's not entirely clear what you're trying to accomplish. Do you want a globally accessible, mutable list of Client objects? Or do you want to have a single globally accessible Client instance that you want to put in a list? - Aaron Novstrup

2 Answers

2
votes

This isn't a global variable thing. Rather, you want to say this:

val lst = List(client1, client2)

However, I disagree somewhat with the other answers. Scala isn't just a functional language. It is both functional (maybe not as purely as it should be if you ask the Clojure fans) and object-oriented. Therefore, your OO expertise translates perfectly.

There is nothing wrong with global variables per se. The concern is mutability. Prefer val to var as I did. Also, you need to use object for singletons rather than the static paradigm you might be used to from Java.

1
votes

The error you quote is unrelated to your attempt to create a global variable. You have missing () after the List[Client].

If you must create a global variable, you can put it in an object like Foo and reference it from other objects using Foo.numMax if the variable is called numMax.

However, global variables are discouraged. Maybe pass the data you need into the functions that need it instead. That is the functional way.