1.

What is a Trait?

Answer»

A trait is like a Java interface declaring a SET of methods and fields. The difference is that the members of a trait may not be abstract. If a class extends a trait, it should implement the abstract methods and fields declared by the trait. On the other hand, it may or may not override those methods having bodies. For example,

trait Comparable[T] { def compare(other: T): Int; def greaterThan (other: T) = compare(other) > 0 def lessThan (other: T) = compare(other) < 0 def isEqualTo (other: T) = compare(other) == 0 } trait Loggable { def LOG(out:PRINTWRITER) }


Traits help us to build rich interfaces where a number of methods define their body in terms of a few abstract methods. This is useful when we INTEND to extend the functionalities of a trait without breaking the client code.

Traits are also very useful in mixing features in a TYPE. A class can extend multiple traits. Moreover, one instance of a class can be created mixing in a number of traits inline as in:

class A(val x:Int) val a = new A(10) with Comparable[A] with Loggable { override def compare(other: A):Int = this.x - other.x override def log(o: PrintWriter):Unit = o.print(this.toString) }


These features provide with a lot of flexibility to play with object creation with different attributes and behavior.



Discussion

No Comment Found