Scala Features – A Comprehensive Guide


1. Introduction to Scala Features

In this Scala programming tutorial, you will learn what is Scala programming language, what is Scala language used for, how scala is both object oriented and functional, how scala is statically typed and extensible and other special Scala features that makes it the choice of programmers and creates Comparison between Java vs Scala.

The name Scala is the abbreviation of the term SCAlable Language. Martin Odersky and his group created the language in 2003 to provide a high-performance, concurrent-ready environment for functional programming and object-oriented programming on the java virtual machine(JVM) platform. Scala is modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant and type-safe way. It smoothly integrates features of object-oriented and functional language. The main features of Scala are as follows –

SCALA FEATURES

2. Scala is Object-Oriented

Scala is pure object-oriented language in the sense that every value is an object. Type and behaviour of the object are described by classes and traits.

3. Scala is functional

Scala is also a functional language in the sense that every function in scala is a value and every value is an object, which makes every function an object.

  • Scala provides a lightweight syntax for defining anonymous functions, also called Function literals. Function literals are nameless functions. Their concept and use of Arrow syntax have many names like – lambda expressions, lambdas, function0, function1, function2…..
  • Scala supports higher order functions, a function which take function as input or function as a return type is called higher order function.
  • Scala allows functions to be nested and Currying.
  • Scala case classes are instantiable classes that include several automatically generated methods. All these methods are based on the class parameter lists.
  • Scala’s built-in supports for pattern matching model algebraic types used in many functional programming languages.
  • Singleton objects provide a convenient way to group functions that aren’t members of a class.
  • Sequence comprehensions are useful for formulating queries.

4. Scala is Statically Typed:

Scala, unlike some of other statically typed languages (c,pascal,rust,etc.), does not expect users to provide redundant type information. They need not specify a type in most cases, and certainly don’t have to repeat it as well.

Abstractions are used in a safe and coherent manner. In particular, the type system supports:-

  • Generic classes: Scala has built in support for classes parameterized with types. This can restrict the reuse of the class abstraction. Such generic classes are particularly useful for the development of collection classes.
  • Polymorphic methods: Methods in scala can be parameterized by type or values.

Ex-  def dup[T](x: T, n: Int): List[T] = {

if (n == 0 ) Nil

else

x :: dup(x, n – 1)

}

println(dup[Int](3, 4))

println(dup(“three”, 3))

Method dup is parameterized with type T and value parameters x : T and n : Int. Scala type system automatically infers the type of the parameter according to the value.

  • Bounded Type: It can be a specific class or its subtype or base type.
  1. Upper Bound: An upper bound restricts a type to only that type or one of its subtypes. This means that an upper bound defines what a type must be and accepts subtypes through polymorphism. Use upper-bound relation operator ( <: ) to specify an upper bound for a type.
  2. Lower Bound: A lower bound restricts a type to only that type or else one of the base types it extends. Use the lower-bound relation operator ( >: ) to specify a lower bound for a type.
  • Type variance: Whereas adding upper or lower bounds will make type parameters more restrictive, we can add type variance to make type parameters less restrictive. Type variance specifies how a type parameter may adapt to meet a base type or subtype. Here are three generic classes that use each of the variance types.

class InVar[T]   { override def toString = “InVar” }

class CoVar[+T]               { override def toString = “CoVar” }

class ContraVar[-T]  { override def toString = “ContraVar” }

/************ Regular Assignment ************/

val test1: InVar[String] = new InVar[String]

val test2: CoVar[String] = new CoVar[String]

val test3: ContraVar[String] = new ContraVar[String]

The ‘+’ denotes covariance and ‘-‘ denotes contravariance with respect to the type parameter. With respect to type parameters, the class is invariant without a plus or minus. When the type parameters are the same on both sides, the assignments work fine.

  • Compound Types: Sometimes it is necessary to express that the type of an object is a subtype of several other types. In Scala this can be done by compound types, which are intersections of object types. We can specify the type of obj to be both One and Two. This compound type is written like this in Scala:

def OneAndTwo(obj: One with Two): Cloneable = {

//…

}

Compound types can consist of several object types and they may have a single refinement which can be used to narrow the signature of existing object members. The general form is: A with B with C … { refinement }

  • Implicit Parameters and conversions: What if the function executes even if all the parameters are not specified? For the function to operate correctly, the missing, unspecified parameters would have to come from somewhere. One approach would be to define default parameters for your function, but for this, the function must know what the correct values for the missing parameters should be.

Another approach is to use implicit parameters. Here the caller provides the default value in its own namespace. Implicit parameter can be defined as a separate parameter group from the other non-implicit parameters. Local value can be invoked as implicit so it can be used as the implicit parameter. When the function is invoked without specifying a value for the implicit parameter, the local implicit value is then picked up and added to the function invocation. Implicit keyword has to be used to mark a value, variable or function parameter as implicit. An implicit value or variable may be used to fill in for an implicit parameter in a function invocation.

Another implicit feature in Scala is implicit conversions with classes. An implicit class is a type of class that provides an automatic conversion from another class. By automatic conversion from Instances of type A to type B, an instance of type A can appear to have fields and methods as if it were an instance of type B but there are some restrictions about how you can define and use them:

  1. An implicit class must be defined within another object, class, or trait. Fortunately, implicit classes defined within objects can be easily imported to the current name‐space.
  2. They must take a single non implicit class argument.
  3. The implicit class’s name must not conflict with another object, class, or trait in the current namespace. Thus, you cannot use a case class as an implicit class because its automatically generated companion object would break this rule.

5. Scala is Extensible:

The development of domain specific application often requires domain specific language extensions. Scala makes it easy to smoothly add new language in the form of libraries:-

  • Any methods could be used as an infix or postfix operator.
  • Depending on the expected type, closures are constructed automatically.

A join use of both features facilitated the definition of new statements without extending the syntax and without using macro-like meta-programming facilities.

6. Scala runs on the JVM:

Scala is compiled into java byte code. And execute on the Java virtual machine (JVM) which means that java and scala has the common execution platform. The scala compiler compiles scala code into java byte code, which is then executed by the ‘scala’ command that is similar to the java command.

7. Scala can Execute Java Code:

Scala allows you to use all the classes of the java SDK and also your own custom java classes, or your java open source projects.

8. Scala can do Concurrent & Synchronize processing

Scala programming allows you to express general programming patterns effectively which reduces the number of lines and helps the programmer to code in a type-safe way. It allows you to write codes in an immutable manner, which makes it easy to apply concurrency and parallelism.

Refer this tutorial to find some of the best books to learn Scala further.

Leave a comment

Your email address will not be published. Required fields are marked *