Tutorial by Examples

A class in Scala is a 'blueprint' of a class instance. An instance contains the state and behavior as defined by that class. To declare a class: class MyClass{} // curly braces are optional here as class body is empty An instance can be instantiated using new keyword: var instance = new MyClas...
Let's say we have a class MyClass with no constructor argument: class MyClass In Scala we can instantiate it using below syntax: val obj = new MyClass() Or we can simply write: val obj = new MyClass But, if not paid attention, in some cases optional parenthesis may produce some unexpecte...
Singleton Objects Scala supports static members, but not in the same manner as Java. Scala provides an alternative to this called Singleton Objects. Singleton objects are similar to a normal class, except they can not be instantiated using the new keyword. Below is a sample singleton class: object...
Whereas Classes are more like blueprints, Objects are static (i.e. already instantiated): object Dog { def bark: String = "Raf" } Dog.bark() // yields "Raf" They are often used as a companion to a class, they allow you to write: class Dog(val name: String) { } ...
Type check: variable.isInstanceOf[Type] With pattern matching (not so useful in this form): variable match { case _: Type => true case _ => false } Both isInstanceOf and pattern matching are checking only the object's type, not its generic parameter (no type reification), except fo...
Primary Constructor In Scala the primary constructor is the body of the class. The class name is followed by a parameter list, which are the constructor arguments. (As with any function, an empty parameter list may be omitted.) class Foo(x: Int, y: String) { val xy: String = y * x /* now...

Page 1 of 1