Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Scala traits

414 views

Published on

Scala Traits Introduction

Published in: Software
  • Be the first to comment

  • Be the first to like this

Scala traits

  1. 1. Scala Traits Meet Up - June 8, 2015 Jerry Kuru
  2. 2. 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.
  3. 3. How traits work ? Once a trait is defined, it can be mixed in to a class using either the extends or with keywords.
  4. 4. Mixing multiple Traits Override Trait methods as shown below
  5. 5. 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.
  6. 6. Scala's Stackable Trait Pattern Let us look at example https://github.com/jkuru/ScalaTraits
  7. 7. Dynamic Example Credit : Constantin
  8. 8. App Demo https://github.com/jkuru/ScalaTraits
  9. 9. 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.
  10. 10. 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
  11. 11. ?

×