Question | Click to View Answer |
What does the following code print? def triple(x: Int): Int = x * 3
val tripleCopy: (Int) => Int = triple
println(tripleCopy(5))
|
The The following syntax will not work: val tripleCopy = triple
Scala requires that the function inputs and outputs are explicitly defined. Once |
What does the following code print? def quadruple(x: Int): Int = x * 4
val quadrupleCopy = quadruple _
println(quadrupleCopy(5))
|
This placeholder syntax replaces named parameters with the wildcard operator (_). This is equivalent to the following explicit syntax: def quadruple(x: Int): Int = x * 4
val quadrupleCopy: (Int) => Int = quadruple
println(quadrupleCopy(5))
|
What does the following code print? def m(x: Int, y: Int): Int = {
if (x > y) x else y
}
val max: (Int, Int) => Int = m
println(max(88, 99))
|
The |
What does the following code print? Explain the syntax. var fullName = (first: String, last: String) => {
s"$first $last"
}
println(fullName("bob", "loblaw"))
|
The variable This syntax also works. ((first: String, last: String) => {
s"$first $last"
})("bob", "loblaw")
|
What does the following code print? Explain the syntax. var min = (a: Int, b: Int) => {
if (a > b) b else a
}
println(min(78, 44))
|
The variable |
What does the following code print? Explain the syntax. val hi = () => "howdy!"
println(hi())
|
The |
What does the following code print? Explain the syntax. def sad = "meow"
val catCry = sad
println(catCry())
|
This code throws an error. The def sad = "meow"
val catCry = sad _
println(catCry())
|
What does the following code print? Explain the syntax. def play(thing: String): String = {
s"Let's play with $thing"
}
def funify(thing: String, f: String => String): String = {
f(thing) + " and have fun"
}
println(funify("cats", play))
|
The Higher order functions are a critical part of functional programming and we'll see more of them. |