Getting the class for Main in Scala - class

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)

Related

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

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.

What is the type of scala.concurrent.Future?

I try to understand what's the data type of scala.concurrent.Future?
I found the following types from the scala lang documentation, but still unsure the differences between them, and when to use which one?
trait Future[+T] extends Awaitable[T] //for concurrent programming
object Future extends AnyRef //not sure?
http://www.scala-lang.org/api/2.9.3/scala/concurrent/Future.html
http://www.scala-lang.org/api/2.9.3/scala/concurrent/Future$.html
Sorry, but I got an impression that you need first to get some scala basis, what is trait, what is companion object, and other stuff.
Back to your question.
When you want to execute something concurrently, you can wrap it in Future. Your code has some output type (SomeType, could be Unit - equivalent of void), after wrapping into Future you will get Future[SomeType] - it is extension of trait Future[+T]. Than you need some execution context (thread pool) to execute your Future.
Try to find and read "Programming in Scala" written by Martin Odersky, Lex Spoon and Bill Venners, very good for beginners.
Like a collection (List, Array, etc.), a Future is a type that works on/with another type. A useful comparison is the Option type.
Just as an Option[Int] might be an Int value (and it might not), a Future[Int] might not be an Int value yet. It could be that the Int value is still being calculated, or being extracted from a database table, or being retrieved from a distant network location. Whatever the cause, if it's a slow process there's no reason to wait for it. Turn it into a Future[Int] so that your program can go on with other important tasks.
As for the object Future, that is a singleton object that has a handful of methods for handling/manipulating existing Future elements. Future.sequence() is a useful example.
It is unclear whether you are talking about the trait Future or the singleton object Future. I will answer both.
The trait doesn't have a type. It is a type.
All singleton objects foo have the singleton type foo.type, so the singleton object Future has the singleton type Future.type.
In Scala, object is a singleton class, which means, that there only exists a single instance during the runtime of the application. There are several ways to implement singletons in most languages, but most often, you risk some issues such as thread safety. Scala's object takes care of the implementation of this pattern for you.
A common pattern in Scala is creating an object that has the same name as a class, like the one in your example. This is called a companion object. A common use for these is for essentially defining the equivalents of static methods from Java. You can declare methods that are common for all instances, or methods that handle and manipulate instances of the class. In Java, for example, you would declare them as static in the body of the class itself. The companion object helps you with separation of concern in this case.

When should I use a regular class in Scala?

It seems to me that I can make just about anything using object, trait, abstract class and in rare occasions, case class. Most of this is in the form object extends trait. So, I'm wondering, when should I, if ever, use a plain, standard class?
This is not a right place to ask this question
Looks like you are new Scala
Class is a specification for something(some entity) you want to model . It contains behavior and state
There is only one way to declare so called regular class using keyword class
Both trait and abstract class are used for inheritance.
trait is used for inheritance (generally to put common behavior in there). trait is akin to interface in Java. multiple inheritance possible with traits but not abstract class.
A class can extends one class or abstract class but can mixin any number of traits. Traits can have behavior and state.
case class is a nothing but a class but compiler produces some boilerplate code for us to make things easy and look good.
object is used when you want to declare some class but you want to have single instance of the class in the JVM (remember singleton pattern).
If an object performs stateful computations on its members i.e. its members are declared with vars;
Or, even if its member are only declared with vals but those vals store mutable data structures which can be edited in place, then it should be an ordinary (mutable) class akin to a Java mutable object.
The idiomatic way of using Case classes in Scala is as immutable types i.e. all the constructor arguments are vals. We could use vars but then we lose the advantages of case classes like equality comparisons will break over time.
Some advise from Programming in Scala by Odersky et al on deciding between using traits, abstract classes and concrete classes:
If the behavior will not be reused, then make it a concrete class. It is not reusable behavior after all.
If it might be reused in multiple, unrelated classes, make it a trait.
Only traits can be mixed into different parts of the class hierarchy.
If you want to inherit from it in Java code, use an abstract class.
Since traits with code do not have a close Java analog, it tends to be
awkward to inherit from a trait in a Java class. Inheriting from a
Scala class, meanwhile, is exactly like inheriting from a Java class.
As one exception, a Scala trait with only abstract members translates
directly to a Java interface, so you should feel free to define such
traits even if you expect Java code to inherit from it. See Chapter 29
for more information on working with Java and Scala together.
If you plan to distribute it in compiled form, and you expect outside
groups to write classes inheriting from it, you might lean towards
using an abstract class. The issue is that when a trait gains or loses
a member, any classes that inherit from it must be recompiled, even if
they have not changed. If outside clients will only call into the
behavior, instead of inheriting from it, then using a trait is fine.
If efficiency is very important, lean towards using a class. Most Java
runtimes make a virtual method invocation of a class member a faster
operation than an interface method invocation. Traits get compiled to
interfaces and therefore may pay a slight performance overhead.
However, you should make this choice only if you know that the trait
in question constitutes a performance bottleneck and have evidence
that using a class instead actually solves the problem.
If you still do not know, after considering the above, then start by
making it as a trait. You can always
change it later, and in general using a trait keeps more options open.

Scala: Class, Object, APP in Eclipse Scala plug in

In Eclipse plugin, I could create scala Object, APP and class. But what's the difference among these 3. Basically, for object, I implement def main(...), then I could run it. But in class, it seems it is similar to normal Java class, but what's the meaning scala APP, it creates a object which extends APP. What's this meant for?
In the JVM, the starting point of the application is a static method main(String[] args), in some class given to the JVM.
In scala there is no static methods, the equivalent is to put a method in an object (as opposed to class). Putting your main method in a class will not work, it is the same as not marking the method static in java.
App is a helper that allows not to write the main method, and put the code directly in the object body.
object MyApp extends App {
doStuff
}
does the same thing as
object MyApp {
def main(args: Array[String]) {doStuff}
}
(arguments can be used in doStuff under the name args)
Scala has no static methods, so public static void main is not available for classes.
Objects are single entries that better fits the "common to every object of a class" scope. So, oversimplifying things, you can think of Object as a Singleton which "acts as an only-static container" (quote from Scala for Java Refugees). If you think about it, that's the perfect place for a main method, and that's why they are declared there.
The App trait just explores the fact that instructions written inside the body of an Object are executed as part of its initialization. It couples this standard behaviour with some delayed initialization tricks to use the body of an object as the main method. So, you can think about it as a short alternative syntax to create a application entry point. It replaced the naive Application trait that had a lot of shortcomings.
Which one of the two to use is really a matter of taste, but I tend to stick with the more familiar main method syntax.
Cheers,

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.