Cloud Computing - SCALA

Back to Course

Lesson Description

Lession - #693 SCALA TRAITS

SCALA Traits

An attribute encapsulated method and field definitions, which can then be reused by mixing them into classes. In contrast to class legacy, in which each class should acquire from only one superclass, a class can blend in quite a few traits.

traits are utilized to define object types by indicating the mark of the supported method. Scala additionally permits qualities to be to some extent executed yet traits might not have constructor parameters.

A trait definition seems to be a class definition aside from that it utilizes the keyword trait. Coming up next is the essential model sentence structure of attribute.


trait Equal {
   def isEqual(x: Any>
: Boolean def isNotEqual(x: Any>
: Boolean = !isEqual(x>

This trait comprises of two techniques isEqual and isNotEqual. Here, we have not given any execution for isEqual where as another strategy has its execution. Kid classes broadening a trait can give execution for the un-carried out methods. So a trait is basically the same as what we have unique classes in Java.

Allow us to expect an illustration of attribute Equal contain two methods isEqual(>
and isNotEqual(>
. The trait Equal contain one executed technique that is isEqual(>
so when client characterized class Point broadens the attribute Equal, execution to isEqual(>
strategy in Point class ought to be given.

Here it is expected to know two significant technique for Scala, which are utilized in the following model.

obj.isInstanceOf [Point] To actually look at Type of obj and Point are same are not.

obj.asInstanceOf [Point] implies definite projecting by taking the object obj type and returns the equivalent obj as Point type.

Esteem classes and Universal Traits
Esteem classes are new system in Scala to try not to apportion runtime objects. It contains an essential constructor with precisely one val boundary. It contains just methods (def>
not permitted var, val, settled classes, traits, or objects. Esteem class can't be stretched out by another class. This can be conceivable by broadening your worth class with AnyVal. The typesafety of custom datatypes without the runtime upward. Allow us to take an instances of significant worth classes Weight, Height, Email, Age, and so forth. For this large number of models apportioning memory in the application isn't needed. A worth class not permitted to broaden traits. To allow esteem classes to broaden traits, general traits are presented which reaches out for Any.

trait Printable broadens Any {
   def print(>
: Unit = println(this>
} class Wrapper(val basic: Int>
broadens AnyVal with Printable object Demo { def main(args: Array[String]>
{ val w = new Wrapper(3>
//really requires starting up a Wrapper example } }

\>scalac Demo.scala
\>scala Demo


It will give you the hash code of Wrapper class.