Global Variable in Scala

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 ?


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.


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.

链接地址: http://www.djcxy.com/p/72824.html

上一篇: Scala中的case类如何特别?

下一篇: 全局变量在斯卡拉