Desktop version

Home arrow Computer Science arrow Building Applications with Scala

Source

Scala traits using variable mixing technique at Scala REPL

Following is a Scala traits using variable mixing technique at 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 SportCar {

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

| }

defined trait SportCar scala>

scala>val bmw = new Object with SportCar bmw: SportCar = $anon$1@ed17bee scala>bmw.run

res0: String = Rghhhhh Rghhhhh Rghhhhh.... scala>

Scala is a very powerful language indeed. It's possible to add traits to a variable at runtime. When you define a variable, you can use the with operator after the assignment. This is a very useful feature, because it makes it easier to make function composition. You can have multiple specialized traits and just add them in your variables as you need them.

Scala allows you to create the type alias as well, this is a very simple technique which will increase the readability of your code. It's just a simple alias.

Scala type alias sample in Scala REPL

Following is a Scala type alias sample 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>type Email = String

defined type alias Email

scala>

scala>val e = new Email(" This email address is being protected from spam bots, you need Javascript enabled to view it ")

e: String = This email address is being protected from spam bots, you need Javascript enabled to view it

scala>

When you are coding with Scala, it is highly recommended that you use the type alias and traits for everything, because that way you will get more advantages with your compiler, and you will avoid writing unnecessary code and unnecessary unit tests.

 
Source
Found a mistake? Please highlight the word and press Shift + Enter  
< Prev   CONTENTS   Next >

Related topics