scala traits

11
Scala Traits Meet Up - June 8, 2015 Jerry Kuru

Upload: jerry-kuru

Post on 12-Aug-2015

66 views

Category:

Software


1 download

TRANSCRIPT

Scala TraitsMeet Up - June 8, 2015 Jerry Kuru

What are traits ?

Traits are a fundamental unit of code reuse in Scala. A trait encapsulates method and field definitions, which can then be reused by mixing them into classes.

Traits are a way to inherit from multiple class-like constructs, but they differ in important ways from the multiple inheritance present in many languages. One difference is especially important: the interpretation of super.

How traits work ?

Once a trait is defined, it can be mixed in to a class using either the extends or with keywords.

Mixing multiple Traits

Override Trait methods as shown below

Are trait like Java Interface ?

Traits are like Java interfaces but with concrete methods, but they can actually do much more. Traits can, for example, declare fields and maintain state.

Scala's Stackable Trait Pattern

Let us look at example https://github.com/jkuru/ScalaTraits

Dynamic ExampleCredit : Constantin

App Demo

https://github.com/jkuru/ScalaTraits

When to use traits ?If the behavior will not be reused, then make it a concrete class.

If efficiency is very important, lean towards using a class.Most Java runtimes make a virtual method invocation of a class member a faster operation than an interface method invocation. Traits get compiled to interfaces and therefore may pay a slight performance overhead.

If it might be reused in multiple, unrelated classes, make it a trait.

If you still do not know, after considering the above, then start by making it as a trait. You can always change it later, and in general using a trait keeps more options open.

Credits and Reference http://www.artima.com/scalazine/articles/stackable_trait_pattern.html

Odersky, Martin; Spoon, Lex; Venners, Bill (2010-12-13). Programming in Scala: A Comprehensive Step-by-Step Guide (Kindle Location 4334). Artima Press. Kindle Edition.

Thanks to Constantine for feedback ,app design and code clean up

?