C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Scala program that uses class
class Test {
def print() = {
// Print a greeting.
println("Hello")
}
}
// Create new instance of Test class.
val t = new Test()
t.print()
Output
Hello
Here: We have a Page class, and an Image and Paragraphs traits. A trait is defined in a similar way as a class, but uses the trait keyword.
ComplexPage: This class is based on the Page class, but also adds the Image and Paragraphs traits. It contains all three methods.
Finally: We create a ComplexPage instance and call print, printImages and printParagraphs from the Page class and the two traits.
Scala program that uses traits
class Page {
def print() = {
println("Page")
}
}
trait Image {
def printImages() = {
// Print images.
println("Images")
}
}
trait Paragraphs {
def printParagraphs() = {
// Print paragraphs.
println("Paragraphs")
}
}
// Extend Page.
// ... Add Image and Paragraphs traits.
class ComplexPage extends Page
with Image
with Paragraphs {
}
// Create ComplexPage instance.
// ... Use Page, Image, Paragraphs methods on it.
val example = new ComplexPage()
example.print()
example.printImages()
example.printParagraphs()
Output
Page
Images
Paragraphs