Question 1
What is functional programming ?
Functional programming is a style of programming where pure functions and immutable values are the basic building blocks.
Question 2
Is Scala a functional language ?
Scala is a multi-paradigm programming language, it supports imperative and functional style.
Question 3
What is the difference between ‘val’ and ‘var’.
If the variable is declared with the keyword “val” it means it’s immutable, cannot be reassigned to a new value. Mutable variables are declared with the keyword “var“.
Question 4
What is Option ?
Option is a container which can contains one (represented by Some) or zero (represented by None) elements.
1 2 3 |
val emptyOption = None val nonEmptyOption = Some("value") |
Question 5
What is Type Inference ?
Type Inference is ability of Scala compiler to deduct data type of an expression.
The compiler will infer missing type of variable myString
.
1 2 |
scala> val myString = "Hello World" myString: String = Hello World |
Quesstion 6
What is a recursive function ?
A recursive function is a function that may invoke itself.
1 2 3 4 5 6 |
def f(i: Int): Int = { if(i < 10) f(i+1) else i } |
Quesstion 7
Provide an example of try/catch statement ?
1 2 3 4 5 6 |
try { // ... } catch { case ex:Exception => println(ex.getMessage) } |
Question 8
What is higher-order function ?
Function that takes other function as parameters or return function as return value.
1 2 3 |
def f(arg: Int=> Int): Int => Int= { arg } |
1 2 |
scala> f((a: Int) => a*a )(5) res0: Int = 25 |
Question 9
What is vararg parameter ?
The Scala varargs allows to pass a variable number of arguments to a method.
1 |
def f(arg: String*) = arg.mkString(" ") |
1 2 |
scala> f("one", "two", "three") res2: String = one two three |
Question 10
Provide an example of pattern matching ?
1 2 3 4 |
"one" match { case "one" => 1 case "two" => 2 } |
Question 11
What is a trait ?
Trait is like a class, can contain methods and fields but it can not be instantiated.
1 2 3 4 5 |
trait MyTrait { def f() } |
Question 12
What is a singleton object ?
Singleton object is an object that is defined using object
keyword, there can be only one instance of singleton object. As opposed to class it is not instantiated with new keyword but it is accessed by name.
1 2 3 4 5 |
object myObject { def method() : String = "Hello" } |
1 2 |
scala> myObject.method() res3: String = Hello |
Question 13
What is a Tuple ?
A tuple is an ordered collections of values. Unlike collections they can contains values of different types.
1 |
val myTuple = (1, "element", 10.2) |
To access tuple elements we use accessors fields.
1 2 |
scala> myTuple._1 res4: Int = 1 |