Classes. In Scala 3.3 programs we use classes. A Game class has fields and methods—it has the current score and players. And it can take turns with a play method.
With traits, and the trait keyword, we can extend features of our classes. A Game might be extended to adjust the rules. It might add features or options.
First example. Here we introduce a Test class. On this class we find a method print(). This writes a greeting to the screen. We create a new instance of Test with the new-keyword.
class Test {
def print() = {
// Print a greeting.
println("Hello")
}
}
object Program {
def main(args: Array[String]): Unit = {
// Create new instance of Test class.
val t = new Test()
t.print()
}
}Hello
Traits. A trait is used to extend a class. We can compose a class by adding those traits to its definition. This allows us to combine many capabilities in a class.
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.
Next The Page class is based on the Page class, but also adds the Image and Paragraphs traits. It contains all 3 methods.
Finally We create a ComplexPage instance and call print, printImages and printParagraphs from the Page class and the two 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 {
}
object Program {
def main(args: Array[String]): Unit = {
// Create ComplexPage instance.// ... Use Page, Image, Paragraphs methods on it.
val example = new ComplexPage()
example.print()
example.printImages()
example.printParagraphs()
}
}Page
Images
Paragraphs
Review. Scala provides both functional and object-oriented features. With classes and traits we compose complex models. This is streamlined but conceptually similar to Java.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 19, 2023 (edit link).