Posts

Showing posts with the label scala

A practical guide to Scala Traits

Trait - has a super class of AnyRef   - uses extends  or with for inheriting a trait ( with to inherit multiple traits)   - defines a type   - can be overridden using override  keyword   Trait vs Interface (Java)   - trait can declare fields and main state   - rich vs thin interfaces (every concrete method added to trait makes it richer)   Trait vs Class   - trait can NOT have any class parameters        trait doesn't support coding in this style: class Point(x: Int, y: Int) - super calls are statically bound in classes, but dynamically bound in trait         super.toString  is predicable in classes, but not in trait when mixing   Ordered Trait   Traits as stackable modifications   - order of mixins: right most trait takes effect first   When to use Trait?   - If the behaviour will not be reused, then make it a concrete class   - If it might be reused in multip...

Field overriding Java vs Scala

Inheritance is one of the foundations of object-oriented programming, it sounds straight forward on paper, but when it comes down the specifics, the rules are subtly different from language to language, and I will compare and demonstrate the subtlety with field overriding in Java and Scala . Java way Consider this example for field overriding in Java. public class Parent { protected static String name = "parent" ;      public String getName () {      return this .myName() ;      } } public class Child extends Parent { final static String name = "child" ; } public static void Main ( final String[] args) { final Parent parent = new Parent() ; final Child child = new Child() ; parent.getName() ; // "parent" child.getName() ; // "parent" } If you know Java, it's probably not hard to tell both "getName" results are "parent", and there is a legitimate reason for that, in Java, fields cannot be overr...