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

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.

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.

Scala: get singleton object from class [duplicate]

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)

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)

generically populate a same field in all case classes which have a particular timestamp property

I have case classes which have Option[java.sql.Timestamp] field.
case class BooRow(id:Int, createdTs: Option[java.sql.Timestamp])
case class FooRow(id: Int, name:String, deptId:Int,createdTs:Option[java.sql.Timestamp])
case class BarRow(id:Int,name:String)
looking for a generic solution which is also compile time safe to observe incoming case class instance and if it finds createdTs:Option[java.sql.Timestamp] in it then populate it.
Originally thought started with looking at shapless and had posted this question. Gabriele 's answer is right in the context of that previous question but may be I wasn't clear enough in the question so not sure how to "catch" "implicit not found error for that shapeless solution" (for the case class which doesn't have createdTs field) somehow. Generic function should populate createdTs if found in a case class instance it was passed, if it doesn't find createdTs in an instance of a case class then do nothing.
I have tagged slick for this question because these are slick generated case classes (not the reason for tagging) but I assume this can be a common need (generically populating such timestamp columns) when dealing with slick/databases in general. To clarify, I am not looking for db based solutions (like triggers etc) but something at an application level also without using structural types.
Edit: Providing default value to createdTs in case class declaration is not a desired solution. That will stamp wrong timestamp when case class instance is created for an "update" query.
Depending on how you are expecting to arrive at instances of you case classes, one option might be to ensure the createdTs parameter is given a default value on creation:
case class BooRow(id:Int, createdTs: Option[java.sql.Timestamp] = Some(new java.sql.Timestamp((new java.util.Date).getTime)))
However, it isn't clear from your question if this can cover your particular use case.

Difference between case class and case object?

I am learning Scala and Akka and in my recent lookup for a solution, I found something like
case class TotalTaxResult(taxAmount:Double)
case object TaxCalculationTimeout
What is the difference between the two?
When should I use one over the other?
A case class can take arguments, so each instance of that case class can be different based on the values of it's arguments. A case object on the other hand does not take args in the constructor, so there can only be one instance of it (a singleton, like a regular scala object is).
If your message to your actor does not need any value differentiation, use a case object. For instance, if you had an actor that did some work, and you, from the outside, wanted to tell it to do work, then maybe you'd do something like this:
case object DoWork
...
def receive = {
case DoWork =>
//do some work here
}
But if you wanted some variation in how the work is done, you might need to redefine your message like so:
case class DoWorkAfter(waitTime:Long)
...
def receive = {
case class DoWorkAfter(time) =>
context.system.scheduler.scheduleOnce(time.milliseconds, self, DoWork)
case DoWork =>
//do some work here
}
A case object is a singleton case class. They are used kind of like enumeration values. It can be used in pattern matching just like any other value:
TaxCalculationTimeout match {
case TaxCalculationTimeout => println("hello")
}
When you define a case class, you are creating a template for instances of that class. TotalTaxResult(1.0) and TotalTaxResult(2.0) are two different values of the same type. Whereas there is exactly one TaxCalculationTimeout value.
In simple words, Scala is a Object Oriented and Functional programming language. It have features of functional programming like pattern matching with pure object oriented methodology.
Some times, we need to create singleton object without any value like passing some signal for pattern matching. If scala have not concept of case object we just to need to use enum or equals some string value in matching. But this is not a readability in pure Object Oriented language.. In that scenario we are using Case Object
Case classes are used when we need to create multiple objects with different values.
You can think of these two to be just like a class and an object in general.
When you do a case class ClassName(params list) it creates a blueprint for making objects and case object defines a singleton object in the scope in which it is declared.
Starting with Scala 2.10, you should always use case objects instead of case classes with no arguments.
So when you want to do a pattern match on some values which need arguments you should go for a case class, but if your values don't take arguments then you should use a case object.