Ad space (banner)
Lesson 13 / 20

Inheritance and traits

This lesson covers class inheritance and the trait, which gives several types a shared capability.

A trait is close to an interface in other languages, but it can also carry an implementation. You use it by writing class Name extends TraitName.

The sample code defines trait Speakable { def speak(): String } and implements it with class Dog extends Speakable.

A common early stumble is choosing between a trait and ordinary class inheritance (extends). A Scala class can inherit from only one class, but traits can be combined several at a time with with.

In professional work, it is common to define a capability that cuts across several types — "can make a sound", "can be compared" — as a trait.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Scala directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)