How to answer "why scala provides `object` keyword"? [duplicate] - scala

This question already has answers here:
Why are singleton objects more object-oriented?
(7 answers)
Closed 8 years ago.
Someone asked me: Why scala provides object keyword?
I answer that with object we can:
create single instance on the language level
create new instance of other types as factories
combine different traits
But he said "These are what object can do, but not why".
What should I answer this question?
(I just read some articles about object, can I answer: Because scala want to support module on language level? )

object is there to avoid static members. Scala was designed as a pure object oriented language, and static just isn't object oriented. static also makes code harder to understand as you mix code that just doesn't belong together conceptually. In general, separating static and instance members is a good idea.
Also object reduces boilerplate by implementing the singleton pattern for you and makes useless types less present.
Just compare:
class SomeGlobalService {
private SomeGlobalService instance = null
private SomeGlobalService() {
<constructor code>
}
public static SomeGlobalService getInstance() {
if (instance == null)
instance = new SomeGlobalService
return instance
}
<members>
}
SomeGlobalService.getInstance().<someMember>
To
object SomeGlobalService {
<constructor code>
<members>
}
SomeGlobalService.<someMember>
In the first example the package is polluted by the useless class SomeGlobalService which you most defenetely will never use directly. In scala the type is less visible as it is SomeGlobalService.type.

Related

Static and non-static methods in scala [duplicate]

This question already has answers here:
What is the rationale behind having companion objects in Scala?
(7 answers)
Closed 7 years ago.
As we know we don't have static methods in scala. If we have to achieve that taste we declare that class as object. But the problem is that when we declare class as object then all methods present in that object becomes static. And in class all methods all non-static. What I want is that to have static as well as non static methods in the same class, Is it possible? Definitely it would be possible but how??????
To do what you are trying do in Scala you create an object and a class of same name. Put static in object and instance members in Class version of it. This object is called a companion object.

how scala treat companion object?

I'm new to Scala with Java background.
In java when we want to share any field among different objects of class. we declare that field static.
class Car {
static NO_Of_TYRES = 4;
// some implementation.
public int getCarNoOftyres(){
NO_Of_TYRES; // although it's not a good practice to use static without class name
//but we can directly access static member in same class .
}
}
But in Scala we cannot declare static fields in class, we need to use object(companion object) for that.
In scala we will do like this,
class Car {
println(NO_Of_TYRES); // scala doesn't let us do that. gives error
println(Car.NO_Of_TYRES);// this is correct way.
}
object Car {
val NO_Of_TYRES: Int = 4;
}
I'm just curious, how scala treat companion objects?
what different these two key-words (class and object) makes ?
why does scala not letting us access NO_Of_TYRES directly in class?
Companion objects are singleton class instances (and definitions), just to recall singleton in java is more or less:
class Foo {
private Foo() { }
/* boilerplate to prevent cloning */
private static Foo instance = new Foo();
public static Foo getInstance() { return instance; }
public int bar() { return 5; }
}
and then to call method bar of this object:
Foo.getInstance().bar();
Scala removed all this boilerplate and lets you create equivalent thing with just
object Foo {
def bar: Int = 5
}
and to call it you only need
Foo.bar
now what's the difference between 'object' and 'companion object'? It's actually quite simple - companion object (so the object defined in the same file as a class and having the same name) has access to it's related class private fields and methods, and that's probably why scala authors decided that it should reside in the same file - so that references to private fields are in the same file as their declarations (which I think is always the case both in Java and Scala, unless using reflection magic)
I'd like to reference another answer about the same subject: What are the advantages of Scala's companion objects vs static methods?
See also Section 4.3 of Odersky's book Programming in Scala - Chapter 4 - Classes and Objects
Scala treats everything as pure objects with their instances. In this view a java static member is not part of any instance, it lives a separate and different life.
With the tricks of the keyword object and some syntactic sugar, you can achieve the same result but maintaining the stated principle: a single instance of that object is instantiated and a global access point for the instance is provided.
Scala, as you pointed out, cannot have static variables or methods, as known in Java. Instead, there are singleton objects, which are declared with the keyword object. Calling a method in this objects is like calling a static method in Java, except you are calling the method on a singleton object instead.
If this object has the same name of a class or trait, it is called the companion object of the class/trait. A companion object must be defined inside the same source file as the class/trait. A companion object differs from other objects as it has access rights to the related class/trait that other objects do not. In particular it can access methods and fields that are private in the class/trait.
Companion objects provide us with a means to associate functionality with a class without associating it with any instance of that class. They are commonly used to provide additional constructors

What's the benefit of Scala (singleton) object vs. typical class level artifacts [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I understand one of the main benefits from using object is, they are real objects instead of system wide functionality. But finally those objects are also system wide accessible.
Beside of being more "pure" what additional benefit does scala "objects" offer.
I bet there are a number but I can't really figure out which.
objects are independent entities, e.g. they can be used as method arguments, as target for implicit conversions, and case objects in pattern matching...
objects can inherit from classes or traits
an object has its own type
objects can restrict the access of its members, even for the companion class:
.
object X {
private[this] val z=1
}
class X {
import X._
//won't compile
println(z)
}
The use of singleton objects as a replacement for static containers have as much advantage as OO has over purely imperative programming. After all, static stuff is essentially imperative, and singleton objects are object oriented.
One advantage I can see is that the object will always be lazily initialized. Static on Java will be initialized when a class is accessed even if the static itself is not used.
See this Java code:
class StaticJava {
static String AA = "Static String";
StaticJava() {
}
}
When I call StaticJava constructor, AA will always initialized, even if it is not used.
On Scala:
object StaticScala {
val AA = "Static String"
}
class StaticScala
Since the object StaticScala will be translated to something like StaticScala$, calling the constructor of StaticScala class will not initialize the singleton object.
The real question should be: why using singletons instead of static classes (static method and fields).
For sure one benefit is that removing static simplify compiler and runtime method resolution.
Another benefit is that having singletons supported by the language is very useful when you write you're own code, you don't have to use dirty trick like private constructors and the orrible getInstance() static method. So much cleaner syntax.
Finally static methods and fields are a nightmare for concurrency unwanted sideeffects.
As far as I can tell the advantage is economy of syntax. Now you don't need any static invocation and field referencing nonsense. They are also cleaner than a single element enum for implementing a strategy (that is, a stateless class implementing an interface).
You might argue that they separate out the static parts too.
The other side of that is that mutable statics are already too easy in Java. Scala hides and legitimatises them.

Why are singleton objects more object-oriented?

In Programming in Scala: A Comprehensive Step-by-Step Guide, the author said:
One way in which Scala is more
object-oriented than Java is that
classes in Scala cannot have static
members. Instead, Scala has singleton
objects.
Why is a singleton object more object-oriented? What's the good of not using static members, but singleton objects?
Trying for the "big picture"; most of this has been covered in other answers, but there doesn't seem to be a single comprehensive reply that puts it all together and joins the dots. So here goes...
Static methods on a class are not methods on an object, this means that:
Static members can't be inherited from a parent class/trait
Static members can't be used to implement an interface
The static members of a class can't be passed as an argument to some function
(and because of the above points...)
Static members can't be overridden
Static members can't be polymorphic
The whole point of objects is that they can inherit from parent objects, implement interfaces, and be passed as arguments - static members have none of these properties, so they aren't truly object-oriented, they're little more than a namespace.
Singleton objects, on the other hand, are fully-fledged members of the object community.
Another very useful property of singletons is that they can easily be changed at some later point in time to not be singletons, this is a particularly painful refactoring if you start from static methods.
Imagine you designed a program for printing addresses and represented interactions with the printer via static methods on some class, then later you want to be able to add a second printer and allow the user to chose which one they'll use... It wouldn't be a fun experience!
Singleton objects behave like classes in that they can extend/implement other types.
Can't do that in Java with just static classes -- it's pretty sugar over the Java singleton pattern with a getInstance that allows (at least) nicer namespaces/stable identifiers and hides the distinction.
Hint: it's called object-oriented programming.
Seriously.
Maybe I am missing something fundamentally important, but I don't see what the fuss is all about: objects are more object-oriented than non-objects because they are objects. Does that really need an explanation?
Note: Although it sure sounds that way, I am really not trying to sound smug here. I have looked at all the other answers and I found them terribly confusing. To me, it's kind of obvious that objects and methods are more object-oriented than namespaces and procedures (which is what static "methods" really are) by the very definition of "object-oriented".
An alternative to having singleton objects would be to make classes themselves objects, as e.g. Ruby, Python, Smalltalk, Newspeak do.
For static members, there is no object. The class really just is a namespace.
In a singleton, there is always at least one object.
In all honesty, it's splitting hairs.
It's more object oriented in the sense that given a Scala class, every method call is a method call on that object. In Java, the static methods don't interact with the object state.
In fact, given an object a of a class A with the static method m(), it's considered bad practice to call a.m(). Instead it's recommended to call A.m() (I believe Eclipse will give you a warning). Java static methods can't be overridden, they can just be hidden by another method:
class A {
public static void m() {
System.out.println("m from A");
}
}
public class B extends A {
public static void m() {
System.out.println("m from B");
}
public static void main(String[] args) {
A a = new B();
a.m();
}
}
What will a.m() print?
In Scala, you would stick the static methods in companion objects A and B and the intent would be clearer as you would refer explicitly to the companion A or B.
Adding the same example in Scala:
class A
object A {
def m() = println("m from A")
}
class B extends A
object B {
def m() = println("m from B")
def main(args: Array[String]) {
val a = new B
A.m() // cannot call a.m()
}
}
There is some difference that may be important in some scenarios. In Java you
can't override static method so if you had class with static methods you would not be able to customize and override part of its behavior. If you used singleton object, you could just plug singleton created from subclass.
It's a marketing thing, really. Consider two examples:
class foo
static const int bar = 42;
end class
class superfoo
Integer bar = ConstInteger.new(42);
end class
Now, what are the observable differences here?
in a well-behaved language, the additional storage created is the same.
Foo.bar and Superfoo.bar have exactly the same signatures, access, and so on.
Superfoo.bar may be allocated differently but that's an implementation detail
It reminds me of the religious wars 20 years ago over whether C++ or Java were "really" Object Oriented, since after all both exposed primitive types that aren't "really" objects -- so, for example you can't inherit from int but can from Integer.

Scala - are classes sufficient?

Coming from Java I am confused by the class/object distinction of scala.
Note that I do not ask for the formal difference; there are enough
references on the web which explain this, and there are related questions on
SO.
My questions are:
Why did the designers of scala
choosed to make things more
complicated (compared to Java or
C#)? What disadvantages do I have to
expect if I ignore this distinction
and declare only classes?
Thanks.
Java classes contain two completely different types of members -- instance members (such as BigDecimal.plus) and static members (such as BigDecimal.valueOf). In Scala, there are only instance members. This is actually a simplification! But it leaves a problem: where do we put methods like valueOf? That's where objects are useful.
class BigDecimal(value: String) {
def plus(that: BigDecimal): BigDecimal = // ...
}
object BigDecimal {
def valueOf(i: Int): BigDecimal = // ...
}
You can view this as the declaration of anonymous class and a single instantiation thereof:
class BigDecimal$object {
def valueOf(i: Int): BigDecimal = // ...
}
lazy val BigDecimal = new BigDecimal$object
When reading Scala code, it is crucial to distinguish types from values. I've configured IntelliJ to hightlight types blue.
val ls = List.empty[Int] // List is a value, a reference the the object List
ls: List[Int] // List is a type, a reference to class List
Java also has another degree of complexity that was removed in Scala -- the distinction between fields and methods. Fields aren't allowed on interfaces, except if they are static and final; methods can be overriden, fields instead are hidden if redefined in a subclass. Scala does away with this complexity, and only exposes methods to the programmer.
Finally, a glib answer to your second question: If you don't declare any objects, you're program may never run, as you to define the equivalent of public static void main(String... args) {} in Scala, you need at least one object!
Scala doesn't have any notion of static methods with standard classes, so in those scenarios you'll have to use objects. Interesting article here which provides a good intro:
http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-3
(scroll down to Scala’s Sort-of Statics)
One way to look at it is this. An executing program consists of a community of objects and threads. Threads execute code within the context of objects -- i.e. there is always a "this" object that a thread is executing within. This is a simplification from Java in the sense that in Java, there is not always a "this". But now there is a chicken/egg problem. If objects are created by threads and threads are executed within objects, what object is the first thread initially executing within. There has to be a nonempty set of objects that exist at the start of program execution. These are the objects declared with the object keyword.