Lesson 14 of 15
Traits
Traits
Traits define interfaces (and can include default implementations). Classes extend them:
trait Greetable {
def greet: String
}
class Person(name: String) extends Greetable {
def greet: String = s"Hello, I'm $name"
}
val p = new Person("Alice")
println(p.greet) // Hello, I'm Alice
Default Implementations
trait Named {
def name: String
def shout: String = name.toUpperCase
}
Your Task
Define a trait Shape with an abstract method area: Double. Then define a class Circle(radius: Double) extends Shape that implements area as 3.14159 * radius * radius.
JS Transpiler loading...
Loading...
Click "Run" to execute your code.