In Scala, apply and unapply methods play very important role. They are also very useful in Play Framework in mapping and unmapping data between Form data and Model data.
In simple words,
apply method: To compose or assemble an object from it’s components.
unapply method: To decompose or dis-assemble an object into it’s components.
Scala’s apply method: It is used to compose an object by using its components. Suppose if we want to create a Person object, then use firstName and laststName two components and compose Person object as shown below.
class Person(val firstName: String, val lastName: String)
object Person{
def apply(firstName: String, lastName: String)
= new Person(firstName, lastName)
}
Scala’s unapply method:
It is used to decompose an object into its components. It follows reverse process of apply method. Suppose if we have a Person object, then we can decompose this object into it’s two components: firstName and laststName as shown below.
class Person(val firstName: String, val lastName: String)
object Person{
def apply(firstName: String, lastName: String)
= new Person(firstName, lastName)
def unapply(p: Person): (String,String)
= (p.firstName, p.lastName)
}
In Scala, The main purpose of Auxiliary Constructors is to overload constructors. Like Java, We can provide various kinds of constructors so that use can choose the right one based on his requirement.
Auxiliary Constructor Rules:
NOTE:- If you want to learn about Scala’s Constructors, please refer my Scala posts at: Primary Constructor and Auxiliary Constructor.
As we know from Java background, we use interface to define contact.
However, there is no interface concept in Scala. Even, Scala doesn’t have interface keyword. Scala has a more powerful and flexible concept i.e. trait for this purpose.
Call-by-name means evaluates method/function parameters only when we need them or we access them. If we don’t use them, then it does not evaluate them.
Scala supports both call-by-value and call-by-name function parameters. However, Java supports only call-by-value, but not call-by-name.
Difference between call-by-value and call-by-name:
The major difference between these two are described below:
Call-by-value:
1 def myFunction(a: Int, b: Int) { }
Here both a and b are Call-by-value parameters to myFunction.
Call-by-name:
1 def myFunction(a: Int, b: => Int) { }
Here both a is a Call-by-value parameter and b is Call-by-name to myFunction.
The following are the major advantages of Play/Scala stack to develop web applications:
The four types of identifiers are
Current Scala’s stable is 2.11.@It supports Java SE 7.
The major change or update in Scala 2.12 version is that it supports Java SE 8 or later versions only. Scala 2.12 is not a binary compatible with the 2.11.x series. It’s still in Mile Stone Builds only.
If you want to become a Fullstack Scala Developer, you should learn the following technology stack:
In Scala, Option is used to represent optional values that is either exist or not exist.
Option is an abstract class. Option has two subclasses: Some and None. All three (Option, Some and None) are defined in “scala” package like “scala.Option”.
Option is a bounded collection in Scala, which contains either zero or one element. If Option contains zero elements that is None. If Option contains one element, that is Some.
Some is used to represent existing value. None is used to represent non-existent value.
Example:-
def get(val index: Int): Option[String]
Let us assume that this method is from List. This method has a return type of Option[String]. If List contains elements, this get method returns “Some[String]” element available in that index position. Otherwise, it returns “None” (that is no elements)
Some is a case class and None is an Object. As both are case class/object, we can use them in Pattern Matching very well.
The combination of all these three definitions is known as Option/Some/None Design Pattern in Scala.
In a source code, anonymous functions are called ‘function literals’ and at run time, function literals are instantiated into objects called function values. Scala provides a relatively easy syntax for defining anonymous functions.
In scala to append into a list, use “:+” single value
var myList = List.empty[String]
myList :+= "a"
myList :+= "b"
myList :+= "c"
use++ for appending a list
var myList = List.empty[String]
myList ++= List("a", "b", "c")
The following three are most popular available Build Tools to develop Play and Scala Applications:
In Scala, Either is an abstract class. It is used to represent one value of two possible types. It takes two type parameters: Either[A,B].
It exactly have two subtypes: Left and Right. If Either[A,B] represents an instance A that means it is Left. If it represents an instance B that means it is Right.
This is known as Either/Left/Right Design Pattern in Scala.
Scala is an object functional programming and scripting language for general software applications designed to express solutions in a concise manner.
The following are the Advantages of Functional Programming (FP) or Advantages of Pure Functions:
The following are the major advantages or benefits of a Case class over Normal Classes:
Case class is a class which is defined with “case class” keywords. Case object is an object which is defined with “case object” keywords. Because of this “case” keyword, we will get some benefits to avoid boilerplate code.
We can create case class objects without using “new” keyword. By default, Scala compiler prefixes “val” for all constructor parameters. That’s why without using val or var, Case class’s constructor parameters will become class members, it is not possible for normal classes.
Advantages of case class:
A monad is an object that wraps another object. You pass the Monad mini-programs, i.e functions, to perform the data manipulation of the underlying object, instead of manipulating the object directly. Monad chooses how to apply the program to the underlying object.
There are many Scala-Based Framework to develop RESTful Web Services. Most popular frameworks are:
In scala, you can define a variable using either a, val or var keywords. The difference between val and var is, var is much like java declaration, but val is little different. We cannot change the reference to point to another reference, once the variable is declared using val. The variable defined using var keywords are mutable and can be changed any number of times.
Scala tuples combine a fixed number of items together so that they can be passed around as whole. A tuple is immutable and can hold objects with different types, unlike an array or list.
In Scala, Nothing type have no values that is zero. It does not have any values. It is a subtype of all Value classes and Reference classes.
In Scala, both List and Stream are from Collection API and works almost similar. Both are Immutable collections.
However, there is one main difference between List and Stream in Scala Collection API: That is List elements are evaluated Eagerly and Stream elements are evaluated Lazily that means when we access them.
scala> var list1 = List(1,2,3,4)
list1: List[Int] = List(1, 2, 3, 4)
Here we can observe that all List elements evaluated at the time of creating List object. However, if we do same thing on Stream, we cannot see all elements. We can see only first evaluated element and remaining elements are evaluated lazily as shown below:
scala> var s1 = Stream(1,2,3,4)
s1: scala.collection.immutable.Stream[Int] = Stream(1, ?)
When we want Lazy collection to evaluate elements only when we access them then it’s better to use Stream.
‘Recursion’ is a function that calls itself. A function that calls itself, for example, a function ‘A’ calls function ‘B’, which calls the function ‘C’. It is a technique used frequently in functional programming. In order for a tail recursive, the call back to the function must be the last function to be performed.
In Scala, we can declare a private Primary Constructor very easily. Just define a Primary Constructor as it is and add ‘private’ just after class name and before parameter list as shown below:
class Person private (name: String)
object Person{
def apply(name: String) = new Person(name)
}
As it’s a private constructor, we cannot call it from outside. We should provide a factory method (that is apply method) as shown above and use that constructor indirectly.
The following two popular IDEs support Play and Scala-Based Applications Development:
They support by using Scala Plugins like Eclipse IDE has a Scala IDE for Eclipse to support Play and Scala-Based Applications Development.
IntelliJ IDEA has a plug-in like “Scala Plugin for IntelliJ IDEA” to support “Scala, SBT and Play 2 Framework” based applications.
Yes, By Default, Case Object is Serializable. But normal object is not. We can prove this by using isInstanaceOf method as shown below:
scala> object MyNormalObject
defined object MyNormalObject
scala> MyNormalObject.isInstanceOf[Serializable]
res0: Boolean = false
scala> case object MyCaseObject
defined object MyCaseObject
scala> MyCaseObject.isInstanceOf[Serializable]
res1: Boolean = true
A Diamond Problem is a Multiple Inheritance problem. Some people calls this problem as Deadly Diamond Problem.
In Scala, it occurs when a Class extends more than one Traits which have same method definition.
Unlike Java 8, Scala solves this diamond problem automatically by following some rules defined in Language. Those rules are called “Class Linearization”.
Example:-
trait A{
def display(){ println("From A.display") }
}
trait B extends A{
override def display() { println("From B.display") }
}
trait C extends A{
override def display() { println("From C.display") }
}
class D extends B with C{ }
object ScalaDiamonProblemTest extends App {
val d = new D
d display
}
Here output is “From C.display” form trait C. Scala Compiler reads “extends B with C” from right to left and takes “display” method definition from lest most trait that is C.
Play 2 is completely written in Scala. If we use Java with Play framework, we need to face many issues because Java does not support full FP features.
Scala is the best option to use with Play framework to develop Highly Scalable, Better Performance with Concurrency/Parallelism and Low latency applications, because:
There is no specific rule when you can use traits, but there is a guideline which you can consider.
Play Framework’s default Unit and Functional Testing Framework is Spec@It is very easy to test Play/Scala based applications using Spec2 Framework.
Play Framework’s Default built-in template is “Twirl”. It was developed in Scala. By using these templates, we can develop Play/Scala based applications very easily.
The Built-in or Default Web Server available for Play Framework is Netty Server.
Values and variables are two shapes that come in Scala. A value variable is constant and cannot be changed once assigned. It is immutable, while a regular variable, on the other hand, is mutable, and you can change the value.
The two types of variables are
var myVar : Int=0;
val myVal: Int=1;
Higher Order Function (HOF) is also a function but which performs one, two or both of the following things:
The following are the most popular MVC frameworks available for Scala Language to develop Web Applications:
SCoverage is the Code-coverage tool for Play and Scala based applications.
SCoverage stands for Scala Code-coverage tool. It has three separate plug-ins to supports the following build tools:
Thousands of clients are using Play and Scala in Production. The following list is the more popular clients who are using Play and Scala actively.
Like JPA, Hibernate and Toplink etc ORM Frameworks for Java-based applications, There are many ORM frameworks to use in Play/Scala based applications.
Popular ORM frameworks for Play/Scala based applications:
The following are most popular available Unit Testing, Functional Testing and/or BDD Frameworks for Play/Scala Based applications:
‘Option’ is a Scala generic type that can either be ‘some’ generic value or none. ‘Queue’ often uses it to represent primitives that may be null.
Because Scala supports the following extra features, it is better than Java 8:
Like Checkstyle for Java-Based Applications, Scalastyle is best Scala style checker tool available for Play and Scala based applications.
Scalastyle observes our Scala source code and indicates potential problems with it. It has three separate plug-ins to supports the following build tools:
It has two separate plug-ins to supports the following two IDEs:
Both are used to perform computation, however they have one major difference in Functional Programming world.
A function is a computation unit without side-effect where as a Procedure is also a computation unit with side-effects.
In Scala Collection API,
A class is a definition for a description. It defines a type in terms of methods and composition of other types. A class is a blueprint of the object. While, an object is a singleton, an instance of a class which is unique. An anonymous class is created for every object in the code, it inherits from whatever classes you declared object to implement.
Range is a Lazy Collection in Scala. Range is a class available in ‘scala’ package like ‘scala.Range’. It is used to represent a sequence of integer values. It is an ordered sequence of integers.
Example:-
scala> 1 to 10
res0: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
scala> 1 until 10
res1: scala.collection.immutable.Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9)
If we use Java 8’s Interface with Default methods, we will get Inheritance Diamond Problem. Developer has to solve it manually in Java @It does not provide default or automatic resolution for this problem.
In Scala, we will get same problem with Traits but Scala is very clever and solves Inheritance Diamond Problem automatically using Class Linearization concept.
Anonymous Function is also a Function but it does not have any function name. It is also known as a Function Literal.
The advantages of a Anonymous Function/Function Literal in Scala:
In Scala, we use ‘object’ keyword to define Factory methods. The main purpose of these Factory methods in Scala is to avoid using ‘new’ keyword. Without using ‘new’ keyword we can create objects.
To define Factory methods:
We can use apply method to define Factory methods in Scala. If we have Primary Constructor and Multiple Auxiliary constructors, then we need to define multiple apply methods as shown below.
class Person(val firstName: String, val middleName: String, val lastName: String){
def this(firstName: String, lastName: String){
this(firstName,"",lastName)
}
}
object Person{
def apply(val firstName: String, val middleName: String, val lastName: String)
= new Person(firstName,middleName,lastName)
def apply(val firstName: String, val lastName: String)
= new Person(firstName, lastName)
}
Now we can create Person objects without using new keyword or with new keyword upto your wish.
val p1 = new Person("Scala","Java")
or
val p1 = Person("Scala","Java")