Scala - what is the benefit of Auxiliary constructors always having to call another constructor? - scala

Coming from the Java world, I don't see how the restrictions on the auxiliary constructors in Scala are helpful ..
In Java, I know we can have multiple constructors as long as their signatures are different.
In Scala, the first call in an auxiliary constructor needs to be another auxiliary constructor or the class's primary constructor. Why? Doesn't this make Scala more restrictive?

Scala essentially guarantees that the primary constructor will always be called, so it gives a single point of entry to the class; FOREVER. You ALWAYS know that the primary constructor will be called, no matter which auxiliary constructor you use to create the object.
Did you even experience having all your nice initialization in your (say) argument-less constructor in Java, and then you (in the future) or someone else coming along creating another constructor and then your objects are not correctly initialized and start miss-behaving? Probably not the best design in the world, but I faced this, and it wasn't fun.
Well, in Scala you never have to worry about this, if you have something in your primary constructor it will always be called or else the code will not compile. In my vocabulary it's not a restriction, it's called "Peace of Mind".

Scala doesn't support multiple constructors like Java. While this may seem like an inconvenience, in return you get less boilerplate. And with factory methods in the companion object you end up getting a richer syntax for construction.
Scala needs to have a primary constructor because you can include declarations in it and eliminate the tedious boilerplate of initializing a field in the constructor.
class Rectangle(val width: Int, val height: Int) {
def this(size: Int) = this(size, size)
}
Note that the 'val' keywords in the default constructor declare two public fields. The idiomatic Java equivalent would have a lot more boilerplate (two getters, plus initialization in the constructor).
Actually in practice most developers prefer factory methods in the companion object (e.g. Rectangle(4) instead of new Rectangle(4, 4)), which is more flexible overall.

Related

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).

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.

Scala: Do classes that extend a trait always take the traits properties?

Given the following:
class TestClass extends TestTrait {
def doesSomething() = methodValue + intValue
}
trait TestTrait {
val intValue = 4
val unusedValue = 5
def methodValue = "method"
def unusedMethod = "unused method"
}
When the above code runs, will TestClass actually have memory allocated to unusedValue or unusedMethod? I've used javap and I know that there exists an unusedValue and an unusedMethod, but I cannot determine if they are actually populated with any sort of state or memory allocation.
Basically, I'm trying to understand if a class ALWAYS gets all that a trait provides, or if the compiler is smart enough to only provide what the class actually uses from the trait?
If a trait always imposes itself on a class, it seems like it could be inefficient, since I expect many programmers will use traits as mixins and therefore wasting memory everywhere.
Thanks to all who read and help me get to the bottom of this!
Generally speaking, in languages like Scala and Java and C++, each class has a table of pointers to its instance methods. If your question is whether the Scala compiler will allocate slots in the method table for unusedMethod then I would say yes it should.
I think your question is whether the Scala compiler will look at the body of TestClass and say "whoa, I only see uses of methodValue and intValue, so being a good compiler I'm going to refrain from allocating space in TestClass's method table for unusedMethod. But it can't really do this in general. The reason is, TestClass will be compiled into a class file TestClass.class and this class may be used in a library by programmers that you don't even know.
And what will they want to do with your class? This:
var x = new TestClass();
print(x.unusedMethod)
See, the thing is the compiler can't predict who is going to use this class in the future, so it puts all methods into its method table, even the ones not called by other methods in the class. This applies to methods declared in the class or picked up via an implemented trait.
If you expect the compiler to do global system-wide static analysis and optimization over a fixed, closed system then I suppose in theory it could whittle away such things, but I suspect that would be a very expensive optimization and not really worth it. If you need this kind of memory savings you would be better off writing smaller traits on your own. :)
It may be easiest to think about how Scala implements traits at the JVM level:
An interface is generated with the same name as the trait, containing all the trait's method signatures
If the trait contains only abstract methods, then nothing more is needed
If the trait contains any concrete methods, then the definition of these will be copied into any class that mixes in the trait
Any vals/vars will also get copied verbatim
It's also worth noting how a hypothetical var bippy: Int is implemented in equivalent java:
private int bippy; //backing field
public int bippy() { return this.bippy; } //getter
public void bippy_$eq(int x) { this.bippy = x; } //setter
For a val, the backing field is final and no setter is generated
When mixing-in a trait, the compiler doesn't analyse usage. For one thing, this would break the contract made by the interface. It would also take an unacceptably long time to perform such an analysis. This means that you will always inherit the cost of the backing fields from any vals/vars that get mixed in.
As you already hinted, if this is a problem then the solution is just use defs in your traits.
There are several other benefits to such an approach and, thanks to the uniform access principle, you can always override such a method with a val further down in the inheritance hierarchy if you need to.

Is it appropriate to define a non-trivial Scala case class?

I'm defining a Scala class today, and I think "I need an equals method and a hashCode method; and a copy method would be handy too. I'll turn this into a case class." My class already has a bunch of other code, and is in no way trivial.
So fine, it all works and everything, but when the text books deal with case classes, all of the examples define them for use as value classes or 'data transfer objects'. Is it appropriate to define a non-trivial case class? Is the thought process described above OK, or do I need to think of case classes differently?
A case class provides, equals, hashCode and toString methods based on the main constructor parameters, all of which are turned into val too. In addition, the object companion gets an apply and an unapply methods, again based on the main constructor parameters.
Also, a case class inherits from Serializable and from Product, and should not be extended by other classes.
If all of these things are appropriate for your class, then feel free to declare it as a `case class'.
Feel free, provided it doesn't have descendants. Extending case classes is a bad idea.

Scala - are classes sufficient?

Coming from Java I am confused by the class/object distinction of scala.
Note that I do not ask for the formal difference; there are enough
references on the web which explain this, and there are related questions on
SO.
My questions are:
Why did the designers of scala
choosed to make things more
complicated (compared to Java or
C#)? What disadvantages do I have to
expect if I ignore this distinction
and declare only classes?
Thanks.
Java classes contain two completely different types of members -- instance members (such as BigDecimal.plus) and static members (such as BigDecimal.valueOf). In Scala, there are only instance members. This is actually a simplification! But it leaves a problem: where do we put methods like valueOf? That's where objects are useful.
class BigDecimal(value: String) {
def plus(that: BigDecimal): BigDecimal = // ...
}
object BigDecimal {
def valueOf(i: Int): BigDecimal = // ...
}
You can view this as the declaration of anonymous class and a single instantiation thereof:
class BigDecimal$object {
def valueOf(i: Int): BigDecimal = // ...
}
lazy val BigDecimal = new BigDecimal$object
When reading Scala code, it is crucial to distinguish types from values. I've configured IntelliJ to hightlight types blue.
val ls = List.empty[Int] // List is a value, a reference the the object List
ls: List[Int] // List is a type, a reference to class List
Java also has another degree of complexity that was removed in Scala -- the distinction between fields and methods. Fields aren't allowed on interfaces, except if they are static and final; methods can be overriden, fields instead are hidden if redefined in a subclass. Scala does away with this complexity, and only exposes methods to the programmer.
Finally, a glib answer to your second question: If you don't declare any objects, you're program may never run, as you to define the equivalent of public static void main(String... args) {} in Scala, you need at least one object!
Scala doesn't have any notion of static methods with standard classes, so in those scenarios you'll have to use objects. Interesting article here which provides a good intro:
http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-3
(scroll down to Scala’s Sort-of Statics)
One way to look at it is this. An executing program consists of a community of objects and threads. Threads execute code within the context of objects -- i.e. there is always a "this" object that a thread is executing within. This is a simplification from Java in the sense that in Java, there is not always a "this". But now there is a chicken/egg problem. If objects are created by threads and threads are executed within objects, what object is the first thread initially executing within. There has to be a nonempty set of objects that exist at the start of program execution. These are the objects declared with the object keyword.