Trait

Trait

Traits are abstract data types containing certain fields and methods.
1
trait Greeter {
2
def greet(name: String): Unit =
3
println("Hello, " + name + "!")
4
}
5
class DefaultGreeter extends Greeter
6
class CustomizableGreeter(prefix: String, postfix: String)
7
extends Greeter {
8
override def greet(name: String): Unit = {
9
println(prefix + name + postfix)
10
}
11
}
12
val greeter = new DefaultGreeter()
13
greeter.greet("Scala developer") // Hello, Scala developer!
14
val customGreeter = new CustomizableGreeter("How are you, ", "?")
15
customGreeter.greet("Scala developer") // How are you, Scala developer?
Copied!
methods in trait may be implemented, may not be implemented. Methods declared, but not implmented in trait must be implmented by classes that extend (inherit) the trait
1
trait prime {
2
def isPrime(x: Int): Boolean
3
}
Copied!
You can create class that extends trait
Last modified 1yr ago
Copy link