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

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)

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.

Are there local value/variable in Scala constructor?

In Java I understand class fields as variables that are accessible from the whole everywhere in the class and that kind of describe the state-structure of instances. In Java field are defined outside any method (and this is the only thing that can be outside of methods).
In Scala "outside any method" is the main constructor - in other words: there is no "outside any method". Thus fields are defined in the main constructor. Thus any variable/value in the constructor is a field. Even arguments given to the constructor are automatically class fields and not local constructor variables as in Java.
In case I got all that right: Are there local variables/values in Scala constructors?
If not: Why was it decided that such a thing is not needed?
Clarficiation: I ask about concepts, not a specific case. Also I do not ask about how to work around to get something like local variables (although I would appreciate it if the answer were that there aren't any).
The entire class body is "the contructor".
You can always restrict the scope of any variable to be a small as you like with a pair of braces, so there is no reason to introduce an additional "concept", that serves no specific purpose. Occam's razor.
class Foo(bar: String) { // constructor parameter
val baz = "baz"; // class member
{
val bat = "bat" // "local" variable
println(bar + baz + bat) // all three are visible
}
println(bar + baz) // only first two are accessble
}
println (new Foo("bar").baz) // only class member can be accessed here

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)

Dealing with nested classes in Scala

I am unable to understand how to work with nested classes in Scala esp when I encountered the error below:
class Action {
val entityModelVar = new EntityModel
}
class EntityModel {
class EntityLabel {
....
}
}
The above code-snippet gives an idea about my class structure. Here's two code blocks that puzzle me on how they work.
val actionList=Array[Action](Action1,Action2)
..
val newLabels=actionList(i).test(doc)
actionList(i).retrain(newLabels) //error pointed here
**Error: type mismatch:
found : Seq[a.entityModelVar.EntityLabel]
required : Seq[_13.entityModelVar.EntityLabel] where _13:Action**
However, the following code compiles without any error:
//This works fine
val a=actionList(i)
val newLabels=a.test(doc2)
a.retrain(newLabels)
Also, here is the definition of the retrain function:
def retrain(labels:Seq[entityModelVar.EntityLabel])={
entityModelVar.retrain(labels)
}
and the signature of EntityModel.retrain function:
def retrain(testLabels:Seq[EntityLabel]):Unit
The problem is that the inner class has got to belong to the same instance of the outer class. But is actionList(i) guaranteed to be the same instance between two calls? The compiler doesn't know for certain (maybe another thread fiddles with it? who knows what apply does anyway?), so it complains. The _13 is its name for a temporary variable that it wishes were there to assure that it is the same instance.
Your next one works because the compiler can see that you call actionList(i) once, store that instance, get an inner class from it and then apply it.
So, moral of the story is: you need to make it abundantly obvious to the compiler that your inner class instances match up to their proper outer class, and the best way to do that is to store that outer class in a val where it can't change without you (or the compiler) noticing.
(You can also specify types of individual variables if you break up parameter blocks. So, for instance: def foo(m: EntityModel)(l: m.EntityLabel) would be a way to write a function that takes an outer class an an inner one corresponding to it.)