Menu
Home
Log in / Register
 
Home arrow Computer Science arrow Building Applications with Scala
Source

Scala traits sample code in Scala REPL

Following is a Scala traits sample code in Scala REPL:

$ scala

Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77).

Type in expressions for evaluation. Or try :help.

scala>trait Car

defined trait Car

scala>

scala>trait SportCar {

| val brand:String

| def run():String = "Rghhhhh Rghhhhh Rghhhhh...."

| }

defined trait SportCar scala>

scala>trait Printable {

| def printIt:Unit

| }

defined trait Printable scala>

scala>class BMW extends Car with SportCar with Printable{

| override val brand = "BMW"

| override def printIt:Unit = println(brand + " does " + run() )

| }

defined class BMW scala>

scala>val x1 = new BMW x1: BMW = BMW@22a71081 scala>x1.printIt

BMW does Rghhhhh Rghhhhh Rghhhhh....

scala>

In the preceding code, we created multiple traits. One is called Car, which is the mother trait. Traits support inheritance as well, and we have it with the SportCar trait which extends from the Car trait. The SportCar trait demands a variable called brand, and defines a concrete implementation of the function run. Finally, we have a class called BMW which extends from multiple traits — this technique is called mixing.

 
Source
Found a mistake? Please highlight the word and press Shift + Enter  
< Prev   CONTENTS   Next >
 
Subjects
Accounting
Business & Finance
Communication
Computer Science
Economics
Education
Engineering
Environment
Geography
Health
History
Language & Literature
Law
Management
Marketing
Mathematics
Political science
Philosophy
Psychology
Religion
Sociology
Travel