Question | Click to View Answer |
What does the following code print? object Hello {
def speak = "sup"
}
println(Hello.speak)
|
|
What does the following code print? object Pikachu {
def superpower = "electricity"
}
var p = new Pikachu
println(p.superpower)
|
This code throws an error.
|
What does the following code print? class Simpson {
var color = "yellow"
}
object Bart extends Simpson {
def speak = {
s"I am $color"
}
}
println(Bart.speak)
|
The Objects can inherit from classes, but classes can't inherit from objects. |
What does the following code print? object Cake {
var base = "cookies"
var sauce = "peanut butter"
def apply() = {
s"Give me $base and $sauce"
}
}
println(Cake())
|
|
What does the following code print? trait Cool {
var speak = "I am groovy"
}
object JoeCamel extends Cool
println(JoeCamel.speak)
|
Traits are similar to abstract classes - they can not be instantiated directly, but can be used as parent classes. Traits allow for multiple inheritance, so a single object can inherit from multiple traits. |
What does the following code print? trait Hyper {
var how = "Give caffeine"
}
class Coffee extends Hyper
var myCup = new Coffee
println(myCup.how)
|
The Both classes and objects can be extended with traits. |
What does the following code print? trait Speed {
def run = {
"really fast"
}
}
trait Jump {
def leap = {
"really high"
}
}
object Spiderman extends Speed with Jump {
def describe = {
s"I can run $run and jump $leap"
}
}
println(Spiderman.describe)
|
The Scala allows for multiple inheritance. |
What does the following code print? trait Diva {
var attitude = "horrible"
}
var arianaGrande = new Diva
println(arianaGrande.attitude)
|
This code throws an error. Traits are abstract and cannot be instantiated directly. Objects and classes can inherit from traits, but traits cannot be instantiated directly. This code works. object arianaGrande extends Diva
println(arianaGrande.attitude)
|
What does the following code print? trait X {
var yyy = "hi"
}
trait Y {
var yyy = "bye"
}
object Moo extends X with Y
println(Moo.yyy)
|
This code throws an error. The |