When is new required in scala [duplicate] - scala

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
“new” keyword in Scala
Ive noticed that creating certain instances in Scala you can leave off using new. When is it required that a developer use new? And why do some objects allow you to miss off using it?
Thanks
List("this","is","a","list") creates a List of those four strings; no
new required
Map("foo" -> 45, "bar" ->76) creates a Map of String to Int, no new
required and no clumsy helper class.
Taken from here..

In general the scala collection classes define factory methods in their companion object using the apply method. The List("this","is","a","list") and Map("foo" -> 45, "bar" ->76) are syntactic sugar for calling those apply methods. Using this convention is fairly idiomatic scala.
In addition if you define a case class C(i: Int) it also defines a factory C.apply(i: Int) method which can be called as C(i). So no new needed.
Other than that, the new is required to create objects.

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.

Quick Documentation For Scala Apply Constructor Pattern in IntelliJ IDE

I am wondering if there is a way to get the quick documentation in IntelliJ to work for the class construction pattern many scala developers use below.
SomeClass(Param1,Parma2)
instead of
new SomeClass(param1,Param2)
The direct constructor call made with new obviously works but many scala devs use apply to construct objects. When that pattern is used the Intelij documentation look up fails to find any information on the class.
I don't know if there are documents in IntelliJ per se. However, the pattern is fairly easy to explain.
There's a pattern in Java code for having static factory methods (this is a specialization of the Gang of Four Factory Method Pattern), often along the lines of (translated to Scala-ish):
object Foo {
def barInstance(args...): Bar = ???
}
The main benefit of doing this is that the factory controls object instantiation, in particular:
the particular runtime class to instantiate, possibly based on the arguments to the factory. For example, the generic immutable collections in Scala have factory methods which may create optimized small collections if they're created with a sufficiently small amount of contents. An example of this is a sequence of length 1 can be implemented with basically no overhead with a single field referring to the object and a lookup that checks if the offset is 0 and either throws or returns its sole field.
whether an instance is created. One can cache arguments to the factory and memoize or "hashcons" the created objects, or precreate the most common instances and hand them out repeatedly.
A further benefit is that the factory is a function, while new is an operator, which allows the factory to be passed around:
class Foo(x: Int)
object Foo {
def instance(x: Int) = new Foo(x)
}
Seq(1, 2, 3).map(x => Foo(x)) // results in Seq(Foo(1), Foo(2), Foo(3))
In Scala, this is combined with the fact that the language allows any object which defines an apply method to be used syntactically as a function (even if it doesn't extend Function, which would allow the object to be passed around as if it's a function) and with the "companion object" to a class (which incorporates the things that in Java would be static in the class) to get something like:
class Foo(constructor_args...)
object Foo {
def apply(args...): Foo = ???
}
Which can be used like:
Foo(...)
For a case class, the Scala compiler automatically generates a companion object with certain behaviors, one of which is an apply with the same arguments as the constructor (other behaviors include contract-obeying hashCode and equals as well as an unapply method to allow for pattern matching).

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)

Class mapping Scala, like Orika

Getting started with Scala and hunting around for Orika modules but for Scala. It is possible to create custom property builders in Orika but for stuff like case cases with value fields I would need to (with Scala 2.10+) reflex fields (mirroring) for setting immutables. Assuming there is a native approach with a Scala module?
I know Orika has lot more features but, if you just want to create a copy of an instance to a new instance and change some attributes of the new instance, scala has inbuilt feature for it. Use case classes and you can use copy method on it to create new instances.
case class Bird(name: String, color: String)
scala> val chicken = Bird("twitty", "yellow")
chicken: Bird = Bird(twitty,yellow)
scala> val coq = chicken.copy(color = "red")
coq: Bird = Bird(twitty,red)