# Scala Midterm
**Question 1**
The following Scala construct:
```scala
(x: Int) => x + 1
```
Choose the --> __wrong__ <-- statement:
1. A functional literal
1. __A function definition__
1. An anonymous function
**Question 2**
Consider the following declaration:
```scala
var x = Set("One", "Two")
```
Why is there no type specification for the x object? Choose the right statement:
1. This means that _x_ can take objects of any type during program execution.
1. This means that x is of type __Any__ (the ultimate root type)
1. __It’s assumed that the compiler infers the type of __x__ from the initializer.__
**Question 3**
Consider the following language construct:
```scala
class Point(x: Int, y: Int)
```
This is… (choose the right statement):
1. The full class declaration with two members fields
2. __The full class declaration with the constructor with two parameters__
3. The forward (incomplete) class declaration which assumes that the full declaration will be specified later
**Question 4**
Consider the following declarations:
```scala
var x = 777
```
```scala
var x: Int = 777
```
Choose the right statement:
1. __Both constructs are semantically the same__
1. The first declaration allows _x_ to take values of any type
1. The first declaration states that the value of _x_ is always `777`
**Question 5**
Consider the following function definition:
```scala
def f(x, y): Int = x + y
```
Choose the right statement:
1. The definition is correct: the compiler will infer types of parameters for each call of this function
1. __The definition is incorrect: parameter type should be specified explicitly__
**Question 6**
Consider the following function definition:
```scala
def max(x: Int, y: Int): Int =
if (x > y) x else y
```
Choose the right statement:
1. The definition is incorrect: return statement should specify the value to be returned by the function
2. __The definition is correct: no need to explicitly write the return statement__
**Question 7**
It’s definitely legal to define a function as a class member. Is there anything similar to “static” functions in Scala?
1. __Yes__
2. No
**Question 8**
Are there “local” or “nested” function in Scala?
1. __Yes__
2. No
**Question 9**
Are there “standalone” functions in Scala – that is functions that are defined outside of a class or an enclosed function?
1. Yes
2. __No__
**Question 10**
Consider the following code:
```scala
List(1, -1, 2, -2, 0).filter(x => x > 0)
```
Choose the right statement:
1. The argument of filter is syntactically incorrect: parameter of the function literal should be specified
2. __This is correct construct: the compiler infers the type of the parameter from the context__
**Question 11**
Consider the following declaration:
```scala
val addMore = (x: Int) => x + more
```
Choose the right statement:
1. The declaration is quite correct
2. The declaration is incorrect: unknown more object in the function literal
3. __The validity of the declaration depends on the presence of more declaration in the surrounding context__
**Question 12**
Capturing free variables of the function literals is made…
1. By their values
2. __By references__
3. Both options are possible
When a free variable is captured it’s possible to…
1. Read its value only without modifying it
2. __Read and update the captured variable__
**Question 13**
Is it possible to define a function returning a function in Scala?
1. __Yes__
2. No
If Yes provide a one-line example. If No explain why.
```
def f(x: Int): Int => Int = (y: Int) => x + y
```
**Question 14**
A Scala type is called functional type if…
1. __It has the apply function defined__
2. It has a default constructor
3. It the call operator () defined (as in C++)
**Question 15**
Consider the following code snippet:
```scala
def sum(a: Int, b: Int, c: Int) = a + b + c
sum(1, 2)
```
What’s the meaning of the call:
1. The same as `sum(1, 2, null)`
2. The correct call returning a function
3. __Incorrect syntax__
**Question 16**
Tuple is Scala is ...
1. On of the most fundamental notions many other notions are based on
1. __A technical means for composing arbitrary objects together__
**Question 17**
Choose the right statement:
1. Tuples in Scala are language-defined constructs using parentheses and commas
2. Tuples in Scala are instances of generic library classes
3. __Both statements are correct__
**Question 18**
Suppose _p_ is a tuple with a number of components. What’s the correct syntax for getting access to components:
1. `p(a-constant)`, e.g. `p(5)`
2. `p(an-integer-expression)`, e.g `p(a+7)`
3. `p.a-constant`, e.g `p.5`
4. __`p._a-constant`, e.g. `p._5`__
5. `p._an-integer-expression`, e.g. `p._a+3`
**Question 19**
Assignment in Scala...
1. Is a usual expression whose value is the value of its right part (like in C++)
1. __An expression returning a “special” value of type Unit__
1. Returns no value (like in Pascal)
**Question 20**
Choose the --> __wrong__ <-- statement
Cases in Scala match construct can be...
1. Constants (literals)
1. Object declarations
1. Types
1. Tuples
1. __Function literals__
1. Instances of case-classes
**Question 21**
Choose the --> __wrong__ <-- statement: In Scala...
1. Lists are only immutable objects
2. Arrays are only mutable objects
3. __Sets are only immutable__
4. Maps are both mutable and immutable
**Question 22**
For a function with the following signature
```scala
def function(): Either[Int, Nothing]
```
Is is safe to write following?
```scala
val Left(i) = function()
```
1. __Yes, the pattern is irrefutable__ (specify why)
2. No, there could be a pattern not covered by the deconstructor (specify which)
3. No, it is not possible to deconstruct values outside match-blocks
**Question 23**
What are the two problems with the following code?
```scala
var message = ""
val f1 = Future { message = message + "Hello, " }
val f2 = Future { message = message + "World!" }
println(message)
```
```
1. Futures mutate the state concurrently, which leads to not determenistic results
2. Println does not wait until futures complete, writes an empty string
```
**Question 24**
Given a following function, describe input under which the function call will throw an exception. Assume that integer overflow does not throw.
```scala
def process(ints: List[Int]): Int =
ints.reduce(_ + _)
```
```
Empty list
```
**Question 25**
Given the following expressions:
```scala
val sum = for(x <- c1; y <- c2) yield x + y
val a = c1.flatMap(x => c2.map(y => x + y))
val b = c2.flatMap(x => c1.map(y => x + y))
```
Choose the right statements:
1.__ Expression `sum` and `a` after desugaring are syntactically equivalent__
2. Expression `sum` and `b` after desugaring are syntactically equivalent
2. __Expression `sum` and `a` are semantically equivalent__
2. Expression `sum` and `b` are semantically equivalent
**Question 26**
Given a following sum-type `Ior`:
```scala
sealed trait Ior[+L, +R] {
def map[T](f: R => T): Ior[L, T]
}
final case class Left[+L](value: L) extends Ior[L, Nothing] {
override def map[T](f: Nothing => T): Ior[L, Nothing] = this
}
final case class Right[+R](value: R) extends Ior[Nothing, R] {
// 1
override def map[T](f: R => T): Ior[Nothing, T] = ???
}
final case class Both[+L, +R](left: L, right: R) extends Ior[L, R] {
// 2
override def map[T](f: R => T): Ior[L, T] = ???
}
```
Provide `map` implementations for `Right` and `Both`.
Note: for any `i: Ior[L, R]`, the predicate `i.map(v => v) == i` must be true.
```scala
//1
def map[T](f: R => T): Ior[Nothing, T] =
Right(f(value))
//2
def map[T](f: R => T): Ior[L, T] =
Both(left, f(right))
```
**Question 27**
Consider a following snippet:
```scala
val list: List[Option[Int]] =
List(Some(6), Some(5), None,
Some(3), Some(2), Some(1))
val res =
list
.collect {
case Some(v) => v
}
.takeWhile(_ >= 5)
.reverse
.reduce(_ - _)
```
The `res` is ...:
1. `1`
1. __`-1`__
1. `UnsupportedOperationException`
**Question 28**
In a following stream-based program what will be the output to the console? Assume that the future is completed before program termination.
```scala
val source: Source[Int, NotUsed] = Source(0 until 3)
val flow = Flow[Int].map { i =>
println(i)
i * 2
}
val sinkFold: Sink[Int, Future[Int]] = Sink.fold(0)(_ + _)
implicit val actors: ActorSystem = ActorSystem()
implicit val ec: ExecutionContext = actors.dispatcher
val result: Future[Int] = source.via(flow).runWith(sinkFold)
for {res1 <- result} {
println(res1)
}
```
1. 0 1 2 3 12
2. __0 1 2 6__
3. 6 0 1 2
4. 12 0 1 2 3
**Question 29**
In the program from the previous questions, how are the implicit values are used?
1. __`ec` in the for-comprehension on future__
2. __`actors` in the `runWith` stream materialization__
3. `ec` in the `runWith` stream materialization
4. `actors` in the for-comprehension on future
**Question 30**
Choose the --> __wrong__ <-- statement about case classes:
1. Case classes generate `toString` method
1. Case classes generate `hashCode` method
1. __Case classes generate `clone` method__
1. Case classes generate `equals` method
**Question 31**
Consider a following code snippet:
```scala
val a = Array(1, 2, 3)
var b = Map("one" -> 1, "two" -> 2)
```
Choose the right statements:
1. `a` is an immutable object
2. __`a` is a mutable object__
3. __`b` is an immutable object__
4. `b` is a mutable object
**Question 32**
Type constructor `Function1[I, O]` or `I => O` has two type parameters: `I` – the argument type and `O` – the result type. Fill the table (one for each type parameter):
| | I | O |
| ------------- | - | - |
| Invariant | | |
| Covariant | | * |
| Contravariant | * | |
| Bivariant | | |
**Question 33**
Consider a following code snippet:
```scala
lazy val a = {
println(b)
7 * 8
}
lazy val b = 12 * 12
println("42")
println(s"$a")
println(s"$a")
```
What will be in the standard output after execution?
1. 144 42 42 56
2. 144 42 56 144 56
3. 42 144 42 56
6. __42 144 56 56__
**Question 34**
What is the preferred naming style for variables and class members?
1. snake_case
2. __camelCase__
3. kebab-case
4. PascalCase
**Question 35**
Consider a following function:
```scala
def reverse[T](list: List[T]): List[T] = list match {
case Nil => Nil
case head :: Nil => head :: Nil
case head :: tail =>
tail.last :: reverse(head :: tail.dropRight(1))
}
```
What potential problems may arise?
```
Quadratic complexity in both time and stack, which leads to stack overflow
```
**Question 36**
In typed actors, how can you get a value from actor `service` and operate on it?
1. __Send it a message with `service ! request` containing a reference to your actor__
2. Use `service ? request` and call `foreach` on the future returned by `?`.
3. __Call `context.ask` and in the feedback build a message passed to you.__
4. Invoke a method on the actor as if it were an ordinary object.
**Question 37**
Matthew McConaughey did not take part in one of these movies/series. Find it.
1. Interstellar
2. The Gentlemen
3. __Space Jam__
4. True Detective
**Question 38**
You want to run an integrational test scenario in which an actor spawns several another actors and message passing and processing is done between them. Which testing tool do you choose?
1. `BehaviorTestKit`
2. __`ActorTestKit`__