Learn Scala from Scratch Educative Quiz Answers

Get Learn Scala from Scratch Educative Quiz Answers

Learn how to program in Scala, one of the most popular programming languages in the world right now — not just amongst developers, but even amongst massive companies like Twitter and LinkedIn.

Scala provides you the tools to build scalable programs easily and effectively. It’s a statically typed, high-level language that combines functional programming and object-oriented programming into one flexible package.

This course will help you stay ahead of the curve, make awesome, scalable apps, and learn a highly coveted new programming language. Start learning today.

Enroll on Educative

Challenge 1: Declaring a Variable

Answer:

val myFirstVariable: Int = 100 

print(myFirstVariable)

Challenge 2: Type Casting

Answer:

val newType: Double = oldType

Quiz 1:

Q1. Variables are used for storing data.

  • True
  • False

Q2. What role does the variable name play when declaring a variable?

  • Decides if the variable is immutable or mutable
  • Acts as an identifier for the variable
  • Decides the data type of the variable
  • Declares the initial value of the variable

Q3. Which print satement should be used for printing on mulitple lines?

  • print()
  • println()
  • Both
  • None of the above

Q4. What will be the output of the following code:

val randomNumber: Int = 39
randomNumber = 72
println(randomNumber)
  • 39
  • 72
  • error
  • randomNumber

Q5. What is the default type of a Scala Variable?

  • Immutable
  • Mutable
  • Both
  • None of the above

Q6. Which subclass does the data type Byte come under?

  • AnyVal
  • Anyref
  • Both
  • None of the above

Q7. What is the flow of Scala’s type hierarchy from top to bottom?

  • AnyRef to AnyVal
  • specific to generic
  • AnyVal to AnyRef
  • generic to specific

Q8. What is Scalas supertype?

  • All
  • Each
  • Every
  • Any

Q9. Which of the following is allowed in terms of type casting?

  • Long => Int
  • Double => Float
  • Short => Int
  • Byte => Char

Q10. What are the three requirements for declaring a variable?

  • Variable name, Data type, Initial Value
  • Keyword, Variable name, Initial Value
  • Keyword, Data type, Initial Value
  • Keyword, Variable name, Data type

Challenge 3: Using Multiple Operators

Answer:

val compareCheck = check < 75 && check >= 8


Challenge 4: Temperature Conversion

Answer:

val celsius = (fahrenheit - 32) * (5D / 9D)

Quiz 2:

Q1. There are two ways to call a method in Scala.

  • True
  • False

Q2. Which method call uses the infix notation?

  • Ordinary
  • Operator
  • None of the above
  • All of the above

Q3. How many built-in operators does Scala provide?

  • 4
  • 5
  • 6
  • None of the above

Q4. What is the difference between ordinary method calls and operator method calls?

  • The only difference is the syntax
  • Both calls result in different outputs
  • None of the above
  • All of the above

Q5. Select the correct output for the following code:

val operand1 = 7
val operand2 = 3

println(operand1 / operand2)
  • 2.3333333
  • 3
  • 2
  • None of the above

Q6. Select the correct output for the following code:

val operand1 = 's'
val operand2 = 'q'

println(operand1 <= operand2)
  • false
  • true
  • sq
  • None of the above

Q7. Select the correct output for the following code:

val A = true
val B = true
val exp = A || B

println(false && exp)
  • Exp
  • false
  • true
  • None of the above

Q8. Select the correct output for the following code:

val operand1 = 7
val operand2 = 3

println(operand1 & operand2)
  • 3
  • 7
  • 10
  • None of the above

Q9. Select the correct output for the following code:

var operand1 = 7
var operand2 = 3
operand1 += operand2

println(operand1)
  • 3
  • 7
  • 10
  • None of the above

Q10. Which of the following is correct in terms of operator precedence?

  • <*&
  • !=|^
  • ==:( )
  • None of the above

Challenge 5: Embed a Variable in a String

Answer:

print(s"$name is $age years old.")

Challenge 6: Formatting Strings

Answer:

print(f"The quotient is $quotient%.3f")

Challenge 7: Searching a String

Answer:

  val expressionToFind = "[a-z]{3}".r
  val match1 = expressionToFind.findFirstIn(stringToFindExpression)


Quiz 3:

Q1. What is string interpolation?

  • Embedding strings with numbers
  • Embedding strings with variables
  • Embedding strings with expressions
  • All of the above
  • None of the above

Q2. How many string interpolation methods does Scala provide?

  • 2
  • 3
  • 4
  • None of the above

Q3. What are processed string literals?

  • Strings that require further processing during run time
  • Strings that require further processing during compilation time
  • Modified strings
  • None of the above

Q4. What would the output be of the given code:

println(s"3 + 2 = ${3 + 2}")
  • 5
  • 3 + 2 = 5
  • ${3+2}
  • None of the above

Q5. Which Java method does the f string interpolator represent?

  • fprint()
  • print()
  • printf()
  • None of the above

Q6. What would the output be of the given code:

val insertSeparator = 12345678
println(f"$insertSeparator%,d")
  • 12,345,678
  • 12345678
  • 12.345.678
  • 12%345%678
  • 12 345 678

Q7. What is the difference between the raw string interpolator and the s string interpolator?

  • raw recognizes escape sequences while s doesn’t
  • raw doesn’t recognize escape sequences while s does
  • raw recognizes character literals while s doesn’t
  • raw doesn’t recognize character literals while s does
  • All of the above
  • None of the above

Q8. The split() method can only split at a comma ,.

  • True
  • False

Q9. What encompasses multiline strings?

  • '''
  • """"
  • """
  • None of the above

Q10. What would the output be of the given code:

val regularExp = "[a-z]{4}".r

val replaceIn = "She is four years old "

val replaced = regularExp.replaceFirstIn(replaceIn,"five")

println(replaced)
  • She is five years old
  • She is four years old
  • Error
  • None of the above

Challenge 8: Array of Integers

Answer:

val array1 = Array.range(minRange, maxRange)
val array2 = array1.map(_ * 3)
val finalArray = array2.filter(_ % 2 == 0)


Challenge 9: Appending an Element to a List

Answer:

val finalList = list :+ list(0)


Quiz 4:

Q1. How many collection classes are at the top of the collection library?

  • 2
  • 3
  • 4
  • None of the above
  • All of the above

Q2. What is the difference between an immutable and mutable collection?

  • An immutable collection cannot be updated while a mutable collection can be updated
  • To update an immutable collection, a new collection is created with the updated values
  • To update a mutable collection, values are updated in the original collection
  • All of the above
  • None of the above

Q3. Which collection class does not store a single value more than once?

  • set
  • map
  • seq
  • All of the above
  • None of the above

Q4. Choose the correct syntax for the foreach method.

  • method.foreach(collection)
  • collection.method(foreach)
  • collection.foreach(method)
  • All of the above
  • None of the above

Q5. What will be the output of the following code:

val array1 = Array(1,2,3,4,5)
val array2 = array1.map(_ * 5)
val finalArray = array2.filter(_ % 2 != 0)
finalArray.foreach(println)
  • 10 20
  • 5 15 25
  • 1 2 3 4 5
  • 5 10 15 20 25
  • None of the above

Q6. What will be the output of the following code:

val list1 = 39::27::1::83::Nil
val finalList = 5 +: list1
finalList.foreach(println)
  • 39 27 1 83
  • 39 27 1 83 5
  • 44 32 6 88
  • 5 39 27 1 83
  • None of the above

Q7. What is the difference between a Vector and a List?

  • Lists are linear while Vectors are indexed
  • Vectors are linear while Lists are indexed
  • Vectors are a mutable seq type collection and Lists are an immutable seq type collection
  • Lists are a mutable seq type collection and Vectors are an immutable seq type collection
  • All of the above
  • None of the above

Q8. The following expressions use the Range collection. Which one is incorrect?

  • Option 1
10 to 20
  • Option 2
10 to 20 by 5
  • Option 3
20 from 10
  • Option 4
10 until 20
  • All of the above
  • None of the above

Q9. Why is a Stream called a lazy List?

  • They are created using #:: instead of ::
  • Streams can be infinitely long
  • Streams only compute required elements
  • All of the above
  • None of the above

Challenge 10: Pass or Fail

Answer:

if (percentage >= 60) 
  print("pass")
else 
  print("fail")

Challenge 11: Oven is Ready!

Answer:

while (temperature<375) { 
  temperature += 25
  count +=1
}


Challenge 12: Array of Squares

Answer:

for (i <- 0 until testArray.length) {
  testArray(i) = testArray(i) * testArray(i)
}

Challenge 13: Color Wheel

Answer:

testVariable match {
  case "blue" => print("orange")
  case "yellow" => print("purple")
  case "red" => print("green")
  case _ => print("not a primary color")
}

Quiz 5:

Q1. What are control structures used for?

  • Control structures are used for determining the output of a statement
  • Control structures dictate the flow in which statements are executed
  • Control structures are diagrams used for understanding the flow of execution
  • All of the above
  • None of the above

Q2. Which statements regarding imperative and declarative programming are true? (Multiple correct answers)

  • Imperative programming is how to execute a sequence of code and declarative programming is what a sequence of code should do.
  • Declarative programming is how to execute a sequence of code and imperative programming is what a sequence of code should do.
  • Functional programming is a subset of imperative programming.
  • Functional programming is a subset of declarative programming

Q3. Which statement is depictive of imperative programming?

  • Restart your computer at 5pm
  • Meet me at the movies at 8pm with Sarah and Ben
  • Go to my room and open the closet; you will find the sweater on the right end.
  • All of the above
  • None of the above

Q4. How many control structures does Scala provide?

  • 4
  • 5
  • 6
  • None of the above

Q5. How does Scala bring a functional approach to imperative control structures?

  • In Scala, control structures return values just like functions.
  • In Scala, control structures are functions themselves.
  • In Scala, control structures take arguments like functions.
  • All of the above
  • None of the above

Q6. What will be the output of the following code:

val array = Array(1,2,3,4,5)

for (i <- 0 until array.length) {
  if (array(i) % 2 == 0) {
    println(array(i))
  }
}
  • 1 2 3 4 5
  • 1 3 5
  • There will be no output
  • 2 4
  • None of the above

Q7. What will be the output of the following code:

val constantPattern: Any = List()

constantPattern match {
  case 5 => print("five")
  case true => print("truth")
  case "hello" => print("hi!")
  case Nil => print("the empty list")
  case _ => print("something else")
  • something else
  • the empty list
  • true
  • None of the above

Q8. What will be the output of the following code:

val sequencePattern = Array(1,2,0)

sequencePattern match {
  case Array(0,_,_)  => println("case1")
  case Array(1,_,_)  => println("case2")
  case Array(_,_,0)  => println("case3")
  case _ => println("default")
}
  • case3
  • case1
  • case2
  • case2 case3
  • None of the above

Q9. while is an expression.

  • True
  • False

Q10. How is while different from the other control structures?

  • Unlike the other control structures, it is not an expression.
  • Unlike the other control structures, it doesn’t have a return value.
  • In Scala, the other control structures are preferred over while.
  • All of the above
  • None of the above

Challenge 14: Absolute Value

Answer:

def absolute(x: Double): Double = {
  if (x < 0) -x else x
}


Quiz 6: CBV or CBN?

Q1. evaluate(2,3)

  • CBV
  • CBN
  • same

Q2. evaluate(3+4, 8)

  • CBV
  • CBN
  • same

Q3. evaluate(7, 2*4)

  • CBV
  • CBN
  • same

Challenge 15: Sum of Lists

Answer:

//Solution using match
def sum(numberList: List[Int]): Int = numberList match { 
  case Nil => 0
  case x :: tail => x + sum(tail)
}

Challenge 16: Max with Nested Functions

Answer:

def mainMax(a: Int, b: Int, c: Int): Int = {
  def max(x: Int, y: Int) = {
    if(x > y) x
    else y
  }
  max(a,max(b,c))
}

Challenge 17: Tail Recursion

Answer:

def factorial(x: Int): Int = {
  def loop(accumulator: Int, x: Int): Int = {
    if(x==0) accumulator
    else loop(accumulator*x,x-1)
  }
  loop(1,x)
}

Quiz 7:

Q1. Which keyword is used for defining a function?

  • val
  • var
  • def
  • None of the above

Q2. The following are optional when defining a basic function.

  • function body wrapped in curly brackets and return type of the function
  • parameters wrapped in parenthesis and return type of the function
  • parameter type and function body wrapped in curly brackets
  • parameters wrapped in parenthesis and parameter type
  • None of the above

Q3. What is the basic idea of the substitution model?

  • Evaluation only reduces an expression to a value if it is being used
  • Evaluation reduces expressions to a value.
  • Evaluation reduces a functions arguments to a value
  • All of the above
  • None of the above

Q4. What purpose do CBV and CBN have?

  • They dictate which expressions should be evaluated
  • They dictate the order in which expressions are to be evaluated
  • They determine which expressions are to be terminated
  • All of the above
  • None of the above

Q5. If the CBN evaluation of an expression terminates, then the CBV evaluation of the same expression is not guaranteed to terminate.

  • True
  • False

Q6. What does the following recursive function do?

def mysteryFunction(list: List[Int]): Int = { 
  def mysteryAccum(list: List[Int], theMystery: Int): Int = {
    list match {
      case Nil => theMystery
      case x :: tail =>
        val newMystery = if (x > theMystery) x else theMystery
        mysteryAccum(tail, newMystery)
    }
  }
  mysteryAccum(list, 0)
}
  • returns the minimum value in a given list
  • returns the median (middle value) in a given list
  • returns the maximum value in a given list
  • error
  • All of the above
  • None of the above

Q7. What is the general purpose of Newton’s method?

  • Finding the square root of a number
  • Approximating the square root of a number using improved estimates
  • Approximating solutions using an iterative process
  • All of the above
  • None of the above

Q8. Which function definition will give an error?

  • Option 1
def factorial(x: Int) = {
  def loop(accumulator: Int, x: Int): Int = {
    if(x==0) accumulator
    else loop(accumulator*x,x-1)
  }
  loop(1,x)
}
  • Option 2
def factorial(x: Int): Int = {
  def loop(accumulator: Int, x: Int) = {
    if(x==0) accumulator
    else loop(accumulator*x,x-1)
  }
  loop(1,x)
}
  • Option 3
def factorial(x: Int): Int = {
  def loop(accumulator: Int, x: Int): Int = {
    if(x==0) accumulator
    else loop(accumulator*x,x-1)
  }
  return loop(1,x)
}
  • All of the above
  • None of the above

Q9. What is the benefit of lexical scoping?

  • Removes redundant code
  • Makes definitions outside a block visible to definitions inside a block
  • Permits variable shadowing
  • All of the above
  • None of the above

Q10. Which of the following is a tail recursive function?

  • Option 1
def fib(x: Int): BigInt = {
  def fibHelper(x: Int, prev: BigInt = 0, next: BigInt = 1): BigInt = x match {
    case 0 => prev
    case 1 => next
    case _ => fibHelper(x - 1, next, (next + prev))
   }
   fibHelper(x)
  }
  • Option 2
def sum(ints: List[Int]): Int = ints match { 
  case Nil => 0
  case x :: tail => x + sum(tail)
  }
  • Option 3
def factorial(n: Int): Int = { 
  if (n == 0) 1
  else n * factorial(n-1)
} 
  • All of the above
  • None of the above

Q11. Which of the following statements is true for blocks?

  • When you define something inside a block, it is only visible from within the block.
  • The definitions inside a block, shadow definitions of the same names outside the block.
  • You can define a variable inside a block with the same name as a variable outside a block without it affecting the outside variable.
  • All of the above
  • None of the above

Challenge 18: Write your First Higher-Order Function

Answer:

def arithmeticPrinter(f: (Int , Int) => Int, x: Int, y: Int) = {
    
  print(f(x,y))
}

Challenge 19: Anonymous Functions

Answer:

def arithmeticPrinter(f: (Int,Int) => Int, x: Int, y: Int) = {
  print(f(x,y))
} 

def printAdd(x: Int, y: Int) = {
  arithmeticPrinter((x,y) => x+y, x, y)
}

def printSubtract(x:Int, y: Int) = {
  arithmeticPrinter((x,y) => x-y, x, y)
}

Challenge 20: Using a Curried Function

Answer:

def product(f: Int => Int)(a: Int, b: Int): Int ={
  if(a > b) 1
  else f(a) * product(f)(a+1,b)
}

def fact(n: Int) = product(x=>x)(1,n)

Quiz 8:

Q1. What does it mean for a function to be treated as a first-class value?

  • A function can be passed as a parameter.
  • A function can be returned as a result
  • A function is treated like a basic data value such as an integer
  • All of the above
  • None of the above

Q2. The code snippets below are using functions as function parameters. Which of the following will result in a syntax error?

  • Option 1
def func1(f: Int => Int, x: Int) = {
  print(f(x))
}
  • Option 2
def func2(f: Int => Int, x: Int) = {
  print(f)
}
  • Option 3
def func3(x: Int, f: Int => Int) = {
  print(f(x))
}
  • Option 4
def func4(f: (Int,Int) => Int, x: Int, y: Int) = {
  print(f(x,y))
}
  • All of the above
  • None of the above

Q3. The code snippets below are anonymous functions which return the product of two numbers. Which of the following are the incorrect implementation?

  • Option 1
(x,y) => x*y
  • Option 2
x,y => x*y
  • Option 3
(x:Int, y:Int) => x*y
  • All of the above
  • None of the above

Q4. What is syntactic sugar?

  • Syntax that makes code easier to read and express
  • Syntax which changes the functionality of the code
  • It’s just a cool way of saying ‘sweet syntax!’
  • All of the above
  • None of the above

Q5. Anonymous functions are syntatic sugar because they don’t bring any change to the expressive power of Scala.

  • True
  • False

Q6. The function saySomething, returns an anonymous function. What will be the output of the following code?

def saySomething(prefix: String) = (s: String) => {
  prefix + " " + s
}

def saySomethingElse = saySomething("hello")

print(saySomethingElse("there"))
  • hellothere
  • therehello
  • hello there
  • hello
  • there
  • None of the above

Q7. What is currying?

  • A way of returning functions
  • A way of writing functions with multiple parameter lists
  • The art of making a delicious curry
  • All of the above
  • None of the above

Q8. add is a curried function. What will be the output of the follwoing code?

def add(a: Int)(b: Int) = a + b

val first = add(1)(5) 

val second = add(4)_ 

val third = second(2) 

print(first == third) 
  • 6
  • 4
  • 2
  • true
  • false
  • None of the above

Quiz 9:

Q1. A bluprint is used to create identical copies of the same object.

  • True
  • False

Q2. The members of a class can be divided into the following two parts:

  • methods and variables
  • functions and properties
  • methods and properties
  • All of the above
  • None of the above

Q3. Why is an object known as an instance of a class?

  • Just a naming convention.
  • An object is an instantiated class.
  • An instance a singular occurence of something the same way an object is a single occurence of a class.
  • All of the above
  • None of the above

Q4. The code below declares a EqualShape class and creates its instance sqaure. Why will the code not compile?

class EqualShape{
  var numOfSides: Int = 0
  var lengthOfSides: Int = 0

  def perimeter = numOfSides * lengthOfSides
}

val square = EqualShape 
  • The code will compile
  • Incorrect object declaration
  • Incorrect class declaration
  • Members of the class are incorrectly defined
  • None of the above

Q5. What will be the output of the following code?

class EqualShape{
  var numOfSides: Int = 0
  var lengthOfSides: Int = 0

  def perimeter = numOfSides * lengthOfSides
}

val square = new EqualShape
val triangle = new EqualShape 
square.numOfSides = 4
square.lengthOfSides = 5

print(triangle.perimeter)
  • 0
  • 20
  • Error
  • None of the above

Q6. When we can pass arguments to an object class, this means that the class was defined using…

  • constructor parameters
  • constructors
  • members
  • All of the above
  • None of the above

Q7. What will be the output of the follwoing code?

class Point(xc: Int, yc: Int) {
  var x: Int = xc
  var y: Int = yc

  def move(dx: Int, dy: Int) {
    x = x + dx
    y = y + dy
    println ("Point x location : " + x);
    println ("Point y location : " + y);
   }
}

val point = new Point(5, 10)

point.move(point.x+1, point.y+2)
  • Point x location : 5 Point y location : 10
  • Point x location : 6 Point y location : 12
  • Point x location : 11 Point y location : 22
  • Point x location : 1 Point y location : 2
  • None of the above

Q8. What is the difference bewteen a singleton object and a class?

  • A singleton object is created using the object keyword while a class is created using the class keyword.
  • A singleton object only has a single instance, unlike a class which has multiple instances.
  • A singleton object cannot be created using the new keyword while a class object must be created using the new keyword.
  • All of the above
  • None of the above

Q9. A companion object can access private members of its companion class.

  • True
  • False

Q10. What is the use of stand alone objects?

  • They are used as an entry point of a Scala application.
  • They are used to execute programs.
  • They can be used anywhere in the program, hence, allow easy access.
  • All of the above
  • None of the above
Conclusion:

I hope this Learn Scala from Scratch Educative Quiz Answers would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

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