Scala / Scala interview questions
Scala combines object-oriented and functional programming in one concise, high-level language. Scala runs on the Java platform (Java virtual machine) and is compatible with existing Java programs.
Its JVM and JavaScript runtimes let you build high-performance systems with easy access to huge ecosystems of libraries.
Scala stands for SCAlable LAnguage and is designed and developed by Martin Odersky. Scala was released publicly in early 2004.
Scala supports both Object oriented programming and Functional programming as in Java8.
Scala is a statically-typed Language so type checking is done at compile-time by the compiler, not at run-time. Compiler checks many of the errors at compile-time so the developer would be resolving most of the errors during compile time itself.
- Simple and concise.
- Complete support for OOP concepts.
- Supports all Functional programming features.
- Type safe language.
- Java Interoperability and use of its libraries.
- Better parallel and concurrent programming constructs.
Yes, Java, Scala, C and C++ are strongly typed. Ruby, python, javascript are few examples of dynamically typed/loosely typed meaning that the type checking is done at run-time, not at compile-time by compiler.
yes, scala is pure object oriented language because,
- functions and primitives are also objects in scala.
- Scala does not have static members.
There are 2 types of variables in Scala, val and var. A value variable (val) is constant and its value cannot be changed once assigned. It is immutable, while a regular variable (var), is mutable, and you can change the value.
val exVal: Int=10 // cannot be changed var exVar : Int=11
- Limited user community,
- Backward incompatiblity,
- Difficult to learn few concepts.
- Results in hybrid project using Scala integrating with Java libraries.
The current version of Scala is 2.12.
Martin Oderskey, a German computer scientist, designed and developed Scala language. Scala is initially released on Jan, 2004.
A method is defined in Scala using the def keyword.
def main (args: Array[String]) { }
An object is a singleton instance of a class that does not need to be instantiated by the developer. If an object has the same name that a class, then the object is called a companion object.
An object cannot accept parameter while class can.
Using object keyword we can create a singleton object.
object HelloWorld { def main(args:Array[String]) { println("Hello world!") } }
The difference is, that a val is executed when it is defined whereas a lazy val is executed when it is accessed the first time.
Traits are used to share interfaces and fields between classes. They are similar to Java 8's interfaces. Classes and objects can extend traits but traits cannot be instantiated and therefore have no parameters.
Traits are types containing certain fields and methods. Even multiple traits can be combined.
Yes. Case class can have methods.
Scala has a special type of class called a "case" class. By default, case classes are immutable and compared by value. You can define case classes with the case class keywords.
case class Circle(radius: Double)
You can instantiate case classes without "new" keyword.
val circleA = Circle(5.0) val circleB = Circle(6.0)
There are 39 keywords. They are abstract, case, catch, class, def, do, else, extends, false, final, finally, for, forSome, if, implicit, import, lazy, match, new, null, object, override, package, private, protected, return, sealed, super, this, throw, trait, try, true, type, val, var, while, with and, yield.
Use backtick to access Scala reserved keyword as identifier. For example, use yield with backticks to ignore the Scala's yield and access the Java's Thread class's method yield instead.
Thread.`yield`()
The Unit type is used to define a function that doesn't return data. It is similar to the void keyword in Java.
def main(args: Array[String]) : Unit = { }
You can define classes with the class keyword followed by its name and constructor parameters.
class GreeterClass(prefix: String, suffix: String) { def greet(name: String){ println(prefix + name + suffix) } }
You can make an instance of a class with the new keyword.
val greeter = new Greeterclass("Hello, ", "!") greeter.greet("Welcome to Javapedia.net")
Functions are expressions that take parameters and sometimes no parameters.
You may define an anonymous function (without a name) that returns a given integer plus five.
(y: Int) => y+5
In the above example, left of the => operator is the list of parameters and on the right is the expressions based on parameters.
Functions can have names as well.
val myFunc = (y: Int) => y+5 println(myFunc(2)) //prints 7
Multiple parameters are specified in a comma-separated list and when it takes no parameters, use empty open/close parenthesis.
val getPI = () => 3.14 println(getPI()) // prints 3.14
Functioons is Scala is similar to Lambda expressions in Java 8.
The main method is an entry point of a program. The Java Virtual Machine requires a main method to be named main and take one argument, an array of strings that accepts command line arguments.
object MyMain { def main(args: Array[String]): Unit = println("Hello world!") }
Any is the supertype of all types, also called the top type. It defines certain methods such as equals, hashCode, and toString. Any has two direct subclasses: AnyVal and AnyRef.
If Scala is used in the context of a Java runtime environment, AnyRef corresponds to java.lang.Object.
Class AnyRef is the root class of all the reference types. All types except the value types descend from this class.
class AnyRef extends Any
Yes, although few claim it is not fully functional, it supports many functional programming features than Java8. Scala supports,
- pattern matching,
- Tail recursion,
- Lazy evaluation,
- Function currying,
- Type inference and immutability.
There are 9 predefined types under AnyVal and they are non-nullable. It is Double, Float, Long, Int, Short, Byte, Char, Unit, and Boolean.
Value types can be cast in the following order: Byte -> Short -> Int -> Long -> Float -> Double.
Also Char value type can be casted to Int.
The above orders are unidirectional and other castings lead to compilation error.
You can also cast a reference type to a subtype.
Scala provides the ability to give parameters default values that can be used to allow a caller to omit those parameters as it becomes optional.
class MyClass (defaultVar : String ="Hello") {}
The method parameters also can have default values.
The order of named arguments can be rearranged. However, if some arguments are named and others are not, the unnamed arguments must come first and in the order of their parameters in the method signature.
def printDetails(first: String, last: String): Unit = { println(first + " " + last) } printDetails("John",last = "Doe")
Use underscore (_) following the package name to import all classes.
import employees._
To import only 2 classes from a package use the following structure.
import employees.{Employee,Dept}
Parameters without val or var are private values, visible only within the class.
Yes. Use extends
keyword to extend a trait. If a class extends a trait, then implement any abstract members of the trait using the override
keyword.
Yes. Where a given trait is required, a subtype of the trait can be used instead.
No. Classes can only have one superclass but can many mixins.
Mixins are traits which are used to compose a class. Mixins are added to class using with
keyword. A class can have more than one mixins.
Abstract types are defined using type
keyword and it is used to describe the type of element whose actual type is provided by the concrete implementation.
Traits and abstract classes can have an abstract type member.
Higher-order functions eliminates redundancy in code by grouping common functionality as a function passed to other functions.
Nested method helps structure the code and promotes readability.
Methods may define multiple parameter lists. When a method is called with a fewer number of parameter lists, then this will yield a function taking the missing parameter lists as its arguments which is known as method currying.
Case classes are compared by structure and not by reference.
case class Greeting(message: String) val greet1 = Greeting (Hello) val greet2 = Greeting (Hello) val greetingsAreSame = greet1 == greet2 // true
Even though greet1 and greet2 refer to different objects, the value of each object is equal.
No. When you create a case class with parameters, the parameters are public val
implicitly and the parameter becomes immutable. It is possible to use var
keyword in case classes but this is discouraged.
Traits and classes can be marked sealed
which means all subtypes must be declared in the same file. This assures that all subtypes are known.
sealed abstract class Communication case class VoiceCall() extends Communication case class Message() extends Communication def findPlaceToSit(commtype: Communication): String = commtype match { case a: VoiceCall => "Call him" case b: Message => "Message him" }
sbt is an open-source build tool for Scala and Java projects, similar to Java's Maven and Ant. Its main features are: Native support for compiling Scala code and integrating with many Scala test frameworks.
implicit keyword makes the class's primary constructor available for implicit conversions when the class is in scope.
To create an implicit class, simply place the implicit keyword in front of an appropriate class. They must be defined inside of another trait/class/object.
No, increment/ decrement operators (for example, i++ and ++i) is not supported in Scala. Instead you may have to use i=i+1 or i+=1.
Scala.List represents an immutable collection while Java List is mutable.
Play is a high-velocity web framework for Java and Scala. Play is built on the Akka toolkit. It is lightweight, stateless and uses web-friendly architecture.