Global Variable in Scala - 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.

Related

local object in lua class constructor?

I'm new to Lua "classes" (metatables) and I have a doubt.
In the following constructor code that I wrote, I declared the variable obj as local. But in most examples on the web, this variable is just assigned to without a local declaration. So in my understanding, it becomes a global variable (not efficient from what I understood). But is there a reason for that?
A = {}
A.__index = A
function A:new(obj_init)
local obj = obj_init or {val = 0}
setmetatable(obj, A)
return obj
end
I also noticed that members of the class can be accessed directly, even from another Lua module:
x = A:new{val = 2}
print(x.val)
But is there a way to make val a private member? Maybe also using local?
First, let's look at what these examples you found might have looked like.
Parameters: Implicit locals
function A:new(obj)
obj = obj or {val = 0}
...
end
in this snippet, obj is a local variable. This is because all function parameters in Lua are local variables. We may rewrite the function as follows to highlight this:
function A:new(...)
local obj = ...
obj = obj or {val = 0}
end
I assume this is what you saw e.g. in the PIL. You probably renamed the parameter to obj_init, losing the implicit local declaration of obj.
Global assignment
If you happened to consume particularly bad resources, you might have seen the following:
function A:new(obj_init)
obj = obj_init or {val = 0}
...
end
in this snippet, obj is indeed a global variable. This is very bad for multiple reasons:
Efficiency: You are right - excepting pathological cases, global variables are always slower than local variables as global variables are entries in the (hash part of the) _G table whereas locals are stored in fast registers of the Lua VM.
Code quality: Global pollution: This constructor now has a side effect: It modifies the global variable obj and expects it to not be modified during its execution. This might lead to this function overwriting a global variable obj and, even worse, you may not yield from a coroutine in the constructor now, because you're dependent on a global state which may not be altered.
Private members
The typical way to implement private table fields in Lua is by convention: You may prefix the field names with an underscore to indicate that these fields may not be modified from outside. Of course programmers are free to circumvent this.
Otherwise, the concept of "private" variables doesn't mesh too well with the scripting language nature of Lua; you can shoehorn full-fledged OOP onto Lua using metatables, but it will be neither idiomatic nor efficient.
Upvalues
The most idiomatic way to implement private members in Lua is to have them be upvalues of closures ("accessors"):
A = {}
A.__index = A
function A:new(obj_init)
local obj = {} -- empty object: only member is private
local val = obj.val
-- note: this does not need `self`, thus no `:` is used;
-- for setters you might want to discard `self` for consistency
function obj.getVal()
return val
end
setmetatable(obj, A)
return obj
end
x = A:new{val = 2}
print(x.getVal())
-- val can not be set from outside (excepting the debug library);
-- it is "private" and only accessible through the getter method
The downside is that all functions accessing your private members will have to be instantiated with each object creation.
Note that even upvalues aren't fully "private" as they may be accessed through the debug library.
debug library workarounds
The debug library allows you to inspect the stack. This allows you to tell which method triggered your __index metamethod. You could thus return different values to different callers. This may be nice for a proof-of-concept to showcase Lua's metaprogramming capabilities, but should not be done in practice as it is very inefficient and hacky.

Are there local value/variable in Scala constructor?

In Java I understand class fields as variables that are accessible from the whole everywhere in the class and that kind of describe the state-structure of instances. In Java field are defined outside any method (and this is the only thing that can be outside of methods).
In Scala "outside any method" is the main constructor - in other words: there is no "outside any method". Thus fields are defined in the main constructor. Thus any variable/value in the constructor is a field. Even arguments given to the constructor are automatically class fields and not local constructor variables as in Java.
In case I got all that right: Are there local variables/values in Scala constructors?
If not: Why was it decided that such a thing is not needed?
Clarficiation: I ask about concepts, not a specific case. Also I do not ask about how to work around to get something like local variables (although I would appreciate it if the answer were that there aren't any).
The entire class body is "the contructor".
You can always restrict the scope of any variable to be a small as you like with a pair of braces, so there is no reason to introduce an additional "concept", that serves no specific purpose. Occam's razor.
class Foo(bar: String) { // constructor parameter
val baz = "baz"; // class member
{
val bat = "bat" // "local" variable
println(bar + baz + bat) // all three are visible
}
println(bar + baz) // only first two are accessble
}
println (new Foo("bar").baz) // only class member can be accessed here

Pattern Matching Design

I recently wrote some code like the block below and it left me with thoughts that the design could be improved if I was more knowledgeable on functional programming abstractions.
sealed trait Foo
case object A extends Foo
case object B extends Foo
case object C extends Foo
.
.
.
object Foo {
private def someFunctionSemanticallyRelatedToA() = { // do stuff }
private def someFunctionSemanticallyRelatedToB() = { // do stuff }
private def someFunctionSemanticallyRelatedToC() = { // do stuff }
.
.
.
def somePublicFunction(x : Foo) = x match {
case A => someFunctionSemanticallyRelatedToA()
case B => someFunctionSemanticallyRelatedToB()
case C => someFunctionSemanticallyRelatedToC()
.
.
.
}
}
My questions are:
Is the somePublicFunction() suffering from code smell or even the whole design? My concern is that the list of value constructors could grow quite big.
Is there a better FP abstraction to handle this type of design more elegantly or even concisely?
You've just run into the expression problem. In your code sample, the problem is that potentially every time you add or remove a case from your Foo algebraic data type, you'll need to modify every single match (like in somePublicFunction) against values of Foo. In Nimrand's answer, the problem is in the opposite end of the spectrum: you can add or remove cases from Foo easily, but every time you want to add or remove a behaviour (a method), you'll need to modify every subclass of Foo.
There are various proposals to solve the expression problem, but one interesting functional way is Oleg Kiselyov's Typed Tagless Final Interpreters, which replaces each case of the algebraic data type with a function that returns some abstract value that's considered to be equivalent to that case. Using generics (i.e. type parameters), these functions can all have compatible types and work with each other no matter when they were implemented. E.g., I've implemented an example of building and evaluating an arithmetic expression tree using TTFI: https://github.com/yawaramin/scala-ttfi
Your explanation is a bit too abstract to give you a confident answer. However, if the list of subclasses of Foo is likely to grow/change in the future, I would be inclined to make it an abstract method of Foo, and then implement the logic for each case in the sub classes. Then you just call Foo.myAbstractMethod() and polymorphism handles everything neatly.
This keeps the code specific to each object with the object itself, which is keeps things more neatly organized. It also means that you can add new subclasses of Foo without having to jump around to multiple places in code to augment the existing match statements elsewhere in the code.
Case classes and pattern-matching work best when the set of sub-classes is relatively small and fixed. For example, Option[T] there are only two sub-classes, Some[T] and None. That will NEVER change, because to change that would be to fundamentally change what Option[T] represents. Therefore, it's a good candidate for pattern-matching.

Should I avoid defining 'object' in Scala?

I think 'object' in Scala is pretty similar to Singleton in Java which is not considered to be a good design practice. Singleton to me is like another way to define global variables which is BAD. I wrote some Scala code like this because it's easy and it works but the code looks ugly:
object HttpServer { // I'm the only HttpServer instance in this program.
var someGlobalState: State
def run() {
// do something
}
}
I'm trying to avoid doing this. When is it good to define Scala object?
No. Many Scala-Libraries heavily rely on object.
The main goal of the Singleton-Pattern is that just one instance of the Object can exist. The same holds true for Object.
You may misuse it as global variable but that is not the point.
Object are for example a great place for Factory Methods or a replacement for Modules to hold functions.
Why do you assume that you only want global variables? Global values and methods are really useful. This is most of what you'll use object for in Scala.
object NumericConstant {
val Pi = 3.1415926535897932385 // I probably will not change....
}
object NumericFunctions {
def squared(x: Double) = x*x // This is probably always what we mean...
}
Now, you do have to be careful using global variables, and if you want to you can implement them in objects. Then you need to figure out whether you are being careless (note: passing the same instance of a class to every single class and method in your program is equally problematic), or whether the logic of what you are doing really is best reflected by a single global value.
Here's a really, really bad idea:
object UserCache {
var newPasswordField: String = "foo bar"
}
Two users change their password simultaneously and...well...you will have some unhappy users.
On the other hand,
object UserIDProvider {
private[this] var maxID = 1
def getNewID() = this.synchronized {
var id = maxID
maxID += 1
id
}
}
if you don't do something like this, again, you're going to have some unhappy users. (Of course, you'd really need to read some state on disk regarding user ID number on startup...or keep all that stuff in a database...but you get the point.)
Global variables are not inherently bad. You just need to understand when it's appropriate. And so it follows that object is not inherently bad. For example:
object HelloWorld {
def main(args:Array[String]){
println("Hello World")
}
}
Without going into a long discussion of the topic, I like to think of it this way: "Do I want 'only one' of these things because that best reflects reality? Or is this a lazy shortcut to get things to 'just work'?"
Don't just blindly and broadly apply the "Singleton is bad" rule. There are plenty of cases where "just one" of something makes sense. In your particular case, I'd need more context to give a more specific recommendation.

Scala instance value scoping

Note that this question and similar ones have been asked before, such as in Forward References - why does this code compile?, but I found the answers to still leave some questions open, so I'm having another go at this issue.
Within methods and functions, the effect of the val keyword appears to be lexical, i.e.
def foo {
println(bar)
val bar = 42
}
yielding
error: forward reference extends over definition of value bar
However, within classes, the scoping rules of val seem to change:
object Foo {
def foo = bar
println(bar)
val bar = 42
}
Not only does this compile, but also the println in the constructor will yield 0 as its output, while calling foo after the instance is fully constructed will result in the expected value 42.
So it appears to be possible for methods to forward-reference instance values, which will, eventually, be initialised before the method can be called (unless, of course, you're calling it from the constructor), and for statements within the constructor to forward-reference values in the same way, accessing them before they've been initialised, resulting in a silly arbitrary value.
From this, a couple of questions arise:
Why does val use its lexical compile-time effect within constructors?
Given that a constructor is really just a method, this seems rather inconsistent to entirely drop val's compile-time effect, giving it its usual run-time effect only.
Why does val, effectively, lose its effect of declaring an immutable value?
Accessing the value at different times may result in different results. To me, it very much seems like a compiler implementation detail leaking out.
What might legitimate usecases for this look like?
I'm having a hard time coming up with an example that absolutely requires the current semantics of val within constructors and wouldn't easily be implementable with a proper, lexical val, possibly in combination with lazy.
How would one work around this behaviour of val, getting back all the guarantees one is used to from using it within other methods?
One could, presumably, declare all instance vals to be lazy in order to get back to a val being immutable and yielding the same result no matter how they are accessed and to make the compile-time effect as observed within regular methods less relevant, but that seems like quite an awful hack to me for this sort of thing.
Given that this behaviour unlikely to ever change within the actual language, would a compiler plugin be the right place to fix this issue, or is it possible to implement a val-alike keyword with, for someone who just spent an hour debugging an issue caused by this oddity, more sensible semantics within the language?
Only a partial answer:
Given that a constructor is really just a method ...
It isn't.
It doesn't return a result and doesn't declare a return type (or doesn't have a name)
It can't be called again for an object of said class like "foo".new ("bar")
You can't hide it from an derived class
You have to call them with 'new'
Their name is fixed by the name of the class
Ctors look a little like methods from the syntax, they take parameters and have a body, but that's about all.
Why does val, effectively, lose its effect of declaring an immutable value?
It doesn't. You have to take an elementary type which can't be null to get this illusion - with Objects, it looks different:
object Foo {
def foo = bar
println (bar.mkString)
val bar = List(42)
}
// Exiting paste mode, now interpreting.
defined module Foo
scala> val foo=Foo
java.lang.NullPointerException
You can't change a val 2 times, you can't give it a different value than null or 0, you can't change it back, and a different value is only possible for the elementary types. So that's far away from being a variable - it's a - maybe uninitialized - final value.
What might legitimate usecases for this look like?
I guess working in the REPL with interactive feedback. You execute code without an explicit wrapping object or class. To get this instant feedback, it can't be waited until the (implicit) object gets its closing }. Therefore the class/object isn't read in a two-pass fashion where firstly all declarations and initialisations are performed.
How would one work around this behaviour of val, getting back all the guarantees one is used to from using it within other methods?
Don't read attributes in the Ctor, like you don't read attributes in Java, which might get overwritten in subclasses.
update
Similar problems can occur in Java. A direct access to an uninitialized, final attribute is prevented by the compiler, but if you call it via another method:
public class FinalCheck
{
final int foo;
public FinalCheck ()
{
// does not compile:
// variable foo might not have been initialized
// System.out.println (foo);
// Does compile -
bar ();
foo = 42;
System.out.println (foo);
}
public void bar () {
System.out.println (foo);
}
public static void main (String args[])
{
new FinalCheck ();
}
}
... you see two values for foo.
0
42
I don't want to excuse this behaviour, and I agree, that it would be nice, if the compiler could warn consequently - in Java and Scala.
So it appears to be possible for methods to forward-reference instance
values, which will, eventually, be initialised before the method can
be called (unless, of course, you're calling it from the constructor),
and for statements within the constructor to forward-reference values
in the same way, accessing them before they've been initialised,
resulting in a silly arbitrary value.
A constructor is a constructor. You are constructing the object. All of its fields are initialized by JVM (basically, zeroed), and then the constructor fills in whatever fields needs filling in.
Why does val use its lexical compile-time effect within constructors?
Given that a constructor is really just a method, this seems rather
inconsistent to entirely drop val's compile-time effect, giving it its
usual run-time effect only.
I have no idea what you are saying or asking here, but a constructor is not a method.
Why does val, effectively, lose its effect of declaring an immutable value?
Accessing the value at different times may result in different
results. To me, it very much seems like a compiler implementation
detail leaking out.
It doesn't. If you try to modify bar from the constructor, you'll see it is not possible. Accessing the value at different times in the constructor may result in different results, of course.
You are constructing the object: it starts not constructed, and ends constructed. For it not to change it would have to start out with its final value, but how can it do that without someone assigning that value?
Guess who does that? The constructor.
What might legitimate usecases for this look like?
I'm having a hard time coming up with an example that absolutely
requires the current semantics of val within constructors and wouldn't
easily be implementable with a proper, lexical val, possibly in
combination with lazy.
There's no use case for accessing the val before its value has been filled in. It's just impossible to find out whether it has been initialized or not. For example:
class Foo {
println(bar)
val bar = 10
}
Do you think the compiler can guarantee it has not been initialized? Well, then open the REPL, put in the above class, and then this:
class Bar extends { override val bar = 42 } with Foo
new Bar
And see that bar was initialized when printed.
How would one work around this behaviour of val, getting back all the
guarantees one is used to from using it within other methods?
Declare your vals before using them. But note that constuctor is not a method. When you do:
println(bar)
inside a constructor, you are writing:
println(this.bar)
And this, the object of the class you are writing a constructor for, has a bar getter, so it is called.
When you do the same thing on a method where bar is a definition, there's no this with a bar getter.