Java Magazine, Jan/Feb 2017
ORACLE COM JAVAMAGAZINE JANUARY FEBRUARY 2017 50 jvm languages Following a unification proposed in the Eifel programming language as the uniform access principle users of the improved class will not notice the change from def message to val message You could even transparently opt for a lazy val which is computed on its first access and then cached This also generalizes to mutable fields which are modeled as a getter and setter The following snippet declares an abstract mutable variable in a trait deferring its implementation in terms of its getter and setter to a subclass perhaps adding validation Ive omitted the implementation using the method which is defined in the standard library to throw a NotImplementedError trait T var v Int class Sub extends T def v Int def v_ x Int Unit A trait may also define a concrete val or var member which the compiler implements automatically in the traits subclasses In keeping with the mantra that every method invocation targets an object Scala avoids the static keyword and instead offers direct support for the singleton design pattern through object definitions Its common practice to define a class and an object of the same name at the same time and what would be static methods in Java become methods on the class so called companion object Here I define a singleton instance of the C class instead of creating a new instance explicitly scala object o extends C Hi defined object o scala println o message Hi Because it doesnt introduce new members the object definition corresponds closely to lazy val o new C Hi Perhaps youve spotted another aspect of Scalas uniformity definitions are always introduced by their keyword one of val var def object trait class or type possibly prefixed by some modifiers such as lazy or private Then come the name and the signature and finally is the righthand side Case Classes and Pattern Matching As another example of how Scala nudges you toward immutable design its very convenient to immediately store constructor arguments in an immutable val or if you prefer in a var To make this even more convenient both val and new keywords can be omitted when defining a case class scala case class C x Int defined class C Case classes model immutable structured data They are called case classes because they are so easy to use with the case keyword when pattern matching as in this example When processing data its often convenient to bundle a few values together in a tuple Because tuples are so common Scala ships with a set of TupleN case classes with N fields
You must have JavaScript enabled to view digital editions.