Scala: get singleton object from class [duplicate] - scala

This question already has answers here:
Get companion object of class by given generic type Scala
(5 answers)
Closed 6 years ago.
Is it possible in Scala to get the singleton instance of an object when I only have the class? Consider
object A {}
def getSingletonInstance[T](x: Class[T]): Option[T] = {
// output the singleton, if x is a singleton class i.e. defined by an object
// is this possible?
}
getSingletonInstance(A.getClass) // --> should return Some[A]

There are many questions on SO discussing different ways of doing this.
One of them I referenced in a comment to your question.
Here is another one, using "official" scala reflection: Get companion object instance with new Scala reflection API
If you don't mind an approach, involving a little "hacking" (as in using some unofficial/undocumented/coincident features rather than an official API), you can do it much easier with something like this:
val clazz = Class.forName(x.getName + "$")
val singleton = clazz.getField("MODULE$").get(clazz)
Note that a companion object of class T does not have to be an instance of T, so the declaration of your getSingletonInstance won't always work.
EDIT I did not realize that you were passing the class of the object itself to your function, not the companion class. In that case, you don't need to append it with dollar sign in the above code, and don't even need the first line at all. You can just do x.getField("MODULE$").get(x)

Related

How to `getClass` of a `case class` without constructing one? [duplicate]

This question already has answers here:
Scala equivalent of Java java.lang.Class<T> Object
(2 answers)
Closed 3 years ago.
Suppose you have a Scala case class like this:
case class A(a: Int, b: Int)
How to get the Class representation of it, the one you usually get with .getClass?
What does NOT work:
Calling A.getClass will not give you the class information, but rather the accompanying auto-generated object. You can observe it by calling: A.getClass.getDeclaredFields.toList, which will give you this list: List(public static A$ A$.MODULE$) instead of a and b fields.
Calling A(null, null).getClass does work because we instantiate a dummy object, but it's more verbose, feels dirty, and comes at odds with compiler linters like "wartremover".
Use Scala-s built-in classOf[A]. The correct type will then be automatically inserted by the Scala compiler.

In Scala, why 'case object' and not just 'object'? [duplicate]

This question already has answers here:
Difference between case object and object
(7 answers)
Closed 6 years ago.
I read and understand, case class is to send arguments and create multiple object and case object don't send any arguments and having single object. So that will achieve by object also why case object.
Why is case object important and when? I already gone through this post, but I did not get why case object.
Difference between case class and case object?
Well... an object in Scala can be "roughly" explained as an instance of an anonymous class. Now the difference in a case object and object lies in the difference of that anonymous class being a case class or just a class
To put it more clearly,
object A
// is roughly equivalent to something like
class AnonymousClass12345
val A = new AnonymousClass12345()
Where as for case object,
case object A
// is roughly equivalent to something like,
case class AnonymousClass12345
val A = new AnonymousClass12345()
And now it should be very easy to relate to case class vs class. And as an instance of an anonymous case class, case object gets all the goodies that any instance of any other case class does.
Note :: This answer is meant to provide an inaccurate but easy to understand explanation. A more accurate answer of this question will require not only an understanding of the difference class vs type which is nicely (but not very accurately) discussed in this - answer but also of Scala reflection.

Scala: self => What does it mean? [duplicate]

This question already has answers here:
Explicit self-references with no type / difference with ''this''
(2 answers)
Closed 6 years ago.
When I look at the code of scala.collection.TraversableLike I see that it starts with self =>
What does it mean?
This is usually used as an alias to "this" variable. Why do you even need this? Consider a simple example:
class A{
self=>
def generate = 5
class B{
def generate:Int = {
self.generate+5
}
}
def o = (new B).generate
}
val a = new A
a.o
If you change "self" to "this" you will get StackOverflowException. Why? Because "this.generate" inside the nested class refers to the method "generate" of class B. So in order to get access to the method "generate" of class A we created an alias to "this".
You could have also wrote:
A.this.generate
instead. And it works too.
You might me also interested in this article.
http://www.markthomas.info/blog/92
It's something called self-type annotation and allows two things:
aliasing this (helpful in nested classes or traits, where this would give you the access to the inner class, and self would give you the access to the outer class),
specifying
additional requirements about this (it works very similar to
inheritance then, you can see examples and differences here)

How can I hide my implicit method or disable `LabelledGeneric` for a specific sealed family? [duplicate]

This question already has answers here:
Using context bounds "negatively" to ensure type class instance is absent from scope
(2 answers)
Closed 7 years ago.
I have to use third-party traits which are designed as:
trait Super[T]
trait Sub[T] extends Super[T]
and I have defined the following method to provide instances for arbitrary sealed families:
implicit def subFor[T, Repr](
implicit
gen: LabelledGeneric.Aux[T, Repr],
sg: Lazy[JsonFormat[Repr]]
): Sub[T] = ???
but somewhere else in the code, somebody has already defined
implicit def superFor[T]: Super[T] = ???
for some specific types, e.g. Option and a few others.
Actually, I'd like to use the existing implementations instead of
using my subFor generic implementation. However, because my
method returns Sub[T] and the existing implementation returns
Super[T] I can't see any way to define my implementation in
such a way that it is considered lower priority.
How can I block my subFor from being called for specific types?
Is there some way to disable LabelledGeneric for specific
types, or some priority reducing mechanism that would stop the
compiler from ever looking for my subFor if it already sees a
Super[T]?
If the implicit defs are defined in companion objects, you have to resort to collision-based type computations. But for "some specific types", the defs are usually not in companion objects of the class (e.g. not on object Option). In this case, you can take advantage of the fact that implicits hide each other within a given namespace. So you can just
implicit def superFor[T]: SomeThrowawayType = ???
and their superFor won't work any more. Since you change the return type, it won't collide or anything; it's effectively just gone. Then you can create your own forwarders at whatever priority level you want that explicitly call their defs.
This does require, however, that you import your stuff after theirs (so it shadows theirs). If this seems too fiddly to be relied upon, you'll have to go for the type computation.

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.