Singleton and Companion Objects are made how, are they instances? - scala

I have read how companion and singleton objects can be used to keep static methods, which makes sense. My question is how is this object made or instantiated it? I have read from some sources on how Objects are instances of the class if used as companion objects while others say they are not instances of the class. Then how are the objects existing or being made? Plus the Object would be same class data type I suppose?

My question is how is this object made or instantiated it?
[…]
Then how are the objects existing or being made?
You don't know, shouldn't know, and can't know.
The Scala Language Specification says that they exist. The Scala Language Specification does not say how they are instantiated. Every implementor is free to implement them however they want.
For example, ECMAScript has object literals, so for Scala.js, there is no need for them to be an instance of any class at all. Scala-native is not dependent on any platform, so it can do whatever it wants. Scala-JVM needs to comply with the restrictions of the JVM, where every object needs to be an instance of a class. In Scala-JVM, every singleton object Foo is an instance of a JVM class named Foo$.
Plus the Object would be same class data type I suppose?
The type of a singleton object Foo is the singleton type Foo.type. It's not a class.
I have read from some sources on how Objects are instances of the class if used as companion objects while others say they are not instances of the class.
Instead of reading "some sources", it's much better to just read the source: the Scala Language Specification, specifically section 5.3.2 Case Classes:
A case class definition of 𝑐[tps](ps1)…(ps𝑛) with type parameters tps and value parameters ps implies the definition of a companion object, which serves as an extractor object. It has the following shape:
object 𝑐 {
def apply[tps](ps1)…(ps𝑛): 𝑐[tps] = new 𝑐[Ts](xs1)…(xs𝑛)
def unapply[tps](𝑥: 𝑐[tps]) =
if (x eq null) scala.None
else scala.Some(𝑥.xs11,…,𝑥.xs1𝑘)
}

Each object has its own class, but you can't access the class directly. This class has a constructor without parameters which is called automatically when it's loaded and creates the only instance.
Objects are instances of the class if used as companion objects
Either you misunderstood or you really shouldn't trust these sources. It's possible for a companion object to extend the trait/class it's companion to, but not at all common.

Companion objects are not instances of the class they're companion of, think of them more like a collection of utility methods. If you're familiar with Java - all the method, that you made static in Java (hence they don't belong to a particular instance, but to class in general) would go to Companion object in Scala. Also, companion objects have access to classes private values.
Objects are lazily initialized for you, you don't need to know when and how exactly are they created, just if you call a function from an object - it will be created for you, and there will be only one instance of it.

Related

some peoples are says class is collection of objects and others says class is instance of an object which oop definition is correct?

First of all! Iam new to programming,
In a blog i saw this two definitions . but iam confused .
It says
Class is a instance of an object
and another says
Class is a collection of objecs
Which definition is correct? How?
If both definitions are true? How?
Thank you
Generally speaking, a class is the mold with which you can create an objet. With one class, you create many objects of the same type.
An object is thus an instance of a class (but not the other way around).
Hope it helps
An object is an instance of a class. An object can be instantiated in other classes. A class is definitely not a collection of objects. However, other objects can be created or instantiated inside of a class.
A class is a blueprint to build a specific type of object. Every object is built from a class.
An instance is a specific object built from a specific class. It is assigned to a reference variable that is used to access the instance's properties and methods. The process of making a new instance is called instantiation and is typically done using the new keyword.
A collection of objects is just that, a collection. There are many data structures designed to hold a collection of object, such as arrays, lists, etc.

what its mean by class, object, instance, attribute in object oriented programing ?

i have learned class is a blueprint of structurally identical items, and the items created using class are called instances.
please let me know what are the difference between class, object, instance and attribute in object oriented programming concept. is the object, instance, attribute same?
http://en.wikipedia.org/wiki/Class_(computer_programming)
Typically they are used like so:
class - blueprint for creating object instances; defines properties and methods
object - synonymous with instance usually (sometimes improperly equated with class)
instance - an actual manifestation of a class; the class defines what properties and methods the instance has while the instance holds the values of the object attributes
attribute - typically synonymous with "property" (an object member whose value can be set), but in some dynamic languages this can also include "methods" (an object member which can be called)
Yes, you're definition of a class is correct. You can create multiple objects of the same class. Each object is an instance of the class. The term instance can not only mean the object is an instance of the class, but it can also relate to polymorphism. There is a keyword, in java it is called instanceof. With it, you can not only tell if an object is an instance of the class, but if the object is an instance of a superclass. So, instance, can also be more type-oriented. Attributes are members of the class, like its variables.

Concept of Object, class and member function

So far this is what I understand objects are, I need feedback to know if I'm correct.
A class is made up of member functions. A class also defines types like int does.
An object is defined by that class and then the object calls the member functions within that class (only in the class it was defined by).
Need to know if I'm missing anything or if I'm wrong about something. Thanks
A class is made up of member functions.
Not necessarily, classes can contain data members too.
A class also defines types like int does.
True
Then the object calls the member functions within that class
Once, you go through the concepts of inheritance, you will understand that, an object can call methods of its base classes

Explanation of singleton objects in Scala

I get the coding in that you basically provide an "object SomeClass" and a "class SomeClass" and the companion class is the class declaration and the object is a singleton. Of which you cannot create an instance. So... my question is mostly the purpose of a singleton object in this particular instance.
Is this basically just a way to provide class methods in Scala? Like + based methods in Objective-C?
I'm reading the Programming in Scala book and Chapter 4 just talked about singleton objects, but it doesn't get into a lot of detail on why this matters.
I realize I may be getting ahead of myself here and that it might be explained in greater detail later. If so, let me know. This book is reasonably good so far, but it has a lot of "in Java, you do this", but I have so little Java experience that I sort of miss a bit of the points I fear. I don't want this to be one of those situations.
I don't recall reading anywhere on the Programming in Scala website that Java was a prerequisite for reading this book...
Yes, companion singletons provide an equivalent to Java's (and C++'s, c#'s, etc.) static methods.
(indeed, companion object methods are exposed via "static forwarders" for the sake of Java interop)
However, singletons go a fair way beyond this.
A singleton can inherit methods from other classes/traits, which can't be done with statics.
A singleton can be passed as a parameter (perhaps via an inherited interface)
A singleton can exist within the scope of a surrounding class or method, just as Java can have inner classes
It's also worth noting that a singleton doesn't have to be a companion, it's perfectly valid to define a singleton without also defining a companion class.
Which helps make Scala a far more object-oriented language that Java (static methods don't belong to an object). Ironic, given that it's largely discussed in terms of its functional credentials.
In many cases we need a singleton to stand for unique object in our software system.
Think about the the solar system. We may have following classes
class Planet
object Earth extends Planet
object Sun extends Planet
object is a simple way to create singleton, of course it is usually used to create class level method, as static method in java
Additional to the given answers (and going in the same general direction as jilen), objects play an important role in Scala's implicit mechanism, e.g. allowing type-class-like behavior (as known from Haskell):
trait Monoid[T] {
def zero:T
def sum(t1:T, t2:T):T
}
def fold[T](ts:T*)(implicit m:Monoid[T]) = ts.foldLeft(m.zero)(m.sum(_,_))
Now we have a fold-Function. which "collapses" a number of Ts together, as long as there is an appropriate Monoid (things that have a neutral element, and can be "added" somehow together) for T. In order to use this, we need only one instance of a Monoid for some type T, the perfect job for an object:
implicit object StringMonoid extends Monoid[String] {
def zero = ""
def sum(s1:String, s2:String) = s1 + s2
}
Now this works:
println(fold("a","bc","def")) //--> abcdef
So objects are very useful in their own right.
But wait, there is more! Companion objects can also serve as a kind of "default configuration" when extending their companion class:
trait Config {
def databaseName:String
def userName:String
def password:String
}
object Config extends Config {
def databaseName = "testDB"
def userName = "scott"
def password = "tiger"
}
So on the one hand you have the trait Config, which can be implemented by the user however she wants, but on the other hand there is a ready made object Config when you want to go with the default settings.
Yes, it is basically a way of providing class methods when used as a companion object.

Getting the class for Main in Scala

If I create a singleton object Main with no companion class, is there any way to get the class of that singleton? classOf[Main] gives an error: "not found: type Main".
As it's an instance of a class, you can use the method Main.getClass to pull this one off.
Behind the scenes, the JVM knows that Main is an instance of a class named Main$, and this can be accessed via Java reflection methods if necessary.
Having said all of that, there's usually very little need for reflection in Scala anyway, so you shouldn't really need this unless you're just after an interesting bit of theory.
Singleton objects, aka modules, do not have a "class" as you cannot inherit from them. Think of singleton and class as opposite notions.
They do have a type though:
object Main
def test(a: Main.type): Unit = println("Got: " + a)
test(Main)