var var_name: type = init_value; Mixin: eg. var i : int = 0; trait RichIterator extends AbsIterator { default values: def foreach(f: T => Unit) { private var myvar: T = _ // "_" is a default while (hasNext) f(next)
CHEAT SHEET value }
v.0.1 } scala.Unit is similar to void in Java, except “Every value is an object & every operation is a message send.” Mixin Class Composition: Unit can be assigned the () value. unnamed2: Unit = () The first parent is called the superclass of Iter, PACKAGE whereas the second (and every other, if present) default values: Java style: parent is called a mixin. package com.mycompany.mypkg 0 for numeric types object StringIteratorTest { applies across the entire file scope false for the Boolean type def main(args: Array[String]) { Package "scoping" approach: curly brace delimited () for the Unit type class Iter extends StringIterator(args(0)) package com null for all object types with RichIterator { val iter = new Iter package mycompany iter foreach println { CONSTANT } package scala Prefer val over var. } { form: val var_name: type = init_value; note the keyword "with" used to create a mixin package demo val i : int = 0; composition of the parents StringIterator and { object HelloWorld RichIterator. { STATIC import java.math.BigInteger No static members, use Singleton, see Object TRAITS // just to show nested importing Like Java interfaces, defines object types by def main(args : Array[String]) : Unit = CLASS specifying method signatures, can be partially { Console.println("Hello there!") Every class inherits from scala.Any implemented. See example in Mixin. } 2 subclass categories: } } scala.AnyVal (maps to java.lang.Object) GENERIC CLASS scala.AnyRef class Stack[T] { } // members here } form: abstract class(pName: PType1, } } pName2: PType2...) extends SuperClass Usage: IMPORT with optional constructor in the class definition: object GenericsTest extends Application { class Person(name: String, age: int) extends val stack = new Stack[Int] import p._ // imports all members of p // do stuff here Mammal { // (this is analogous to import p.* in Java) } // secondary constructor import p.x // the member x of p def this(name: String) { note: can also define generic methods // calls to the "primary" constructor import p.{x => a} // the member x of p renamed this(name, 1); // as a INNER CLASS } import p.{x, y} // the members x and y of p import p1.p2.z // the member z of p2, // members here example: } class Graph { // itself member of p1 predefined function classOf[T] returns Scala class Node { import p1._, p2._ // is a shorthand for import var connectedNodes: List[Node] = Nil // p1._; import p2._ class type T def connectTo(node: Node) { implicit imports: if the package java.lang OBJECT (connectedNodes.find(node.equals).isEmpty) { the package scala connectedNodes = node :: connectedNodes A concrete class instance and is a singleton. } and the object scala.Predef object RunRational extends Application } { Import anywhere inside the client Scala file, not just // members here } // members here at the top of the file, for scoped relevance, see } } example in Package section. usage: except operators ending in colon ':' are treated as SELECTION object GraphTest extends Application { right-associative. The else must be present and must result in the val g: Graph = new Graph val n1: g.Node = g.newNode An example is the list-consing operator “::”. where, same kind of value that the if block does x :: y :: zs is interpreted as x :: (y :: val filename = val n2: g.Node = g.newNode if (options.contains("configFile")) n1.connectTo(n2) // legal zs). options.get("configFile") val h: Graph = new Graph val n3: h.Node = h.newNode eg. else def + (other: Complex) : Complex = { "default.properties" n1.connectTo(n3) // illegal! //.... } } ITERATION Inner classes are bound to the outer object, so a node type is prefixed with its outer instance and Prefer recursion over looping. Infix Operator: can't mix instances. Any single parameter method can be used : while loop: similar to Java System exit 0 CASE CLASSES Thread sleep 10 See http://www.scala-lang.org/node/107 for info. for loop: // to is a method in Int that produces a Range unary operators - prefix the operator name with object METHODS/FUNCTIONS "unary_" for (i <- 1 to 10; i % 2 == 0) // the left- def unary_~ : Rational = new Rational(denom, arrow means "assignment" in Scala Methods are Functional Values and Functions are numer) System.out.println("Counting " + i) Objects form: def name(pName: PType1, pName2: i <- 1 to 10 is equivalent to: The Scala compiler will try to infer some meaning for (i <- 1.to(10)) PType2...) : RetType out of the "operators" that have some use override to override a method i % 2 == 0 is a filter, optional predetermined meaning, such as the += operator. override def toString() = "" + re + (if (im < 0) "" else "+") + im + "i" for (val arg <- args) ARRAYS Can override for different return type. maps to args foreach (arg => ...) arrays are classes “=>” separates the function's argument list from its Array[T] body access as function: More to come... def re = real // method without arguments a(i) Anonymous: parameterize with a type (function params) | rt. arrow | function body val hellos = new Array[String](3) REFERENCES (x : int, y : int) => x + y The Busy Developers' Guide to Scala series: MAIN • “Don't Get Thrown for a Loop”, IBM OPERATORS def main(args: Array[String]) All operators are functions on a class. developerWorks return type is Unit Have fixed precedences and associativities: • “Class action”, IBM developerWorks (all letters) • “Functional programming for the object ANNOTATIONS oriented”, IBM developerWorks | See http://www.scala-lang.org/node/106 ^ & Scala Reference Manuals: ASSIGNMENT • “An Overview of the Scala Programming < > = Language” (2. Edition, 20 pages), scala- = ! protected var x = 0 : <- lang.org + - val x <- xs is a generator which produces a • A Brief Scala Tutorial, scala-lang.org / % • “A Tour of Scala”, scala-lang.org sequence of values * (all other special characters) "Scala for Java programmers", A. Sundararajan's Operators are usually left-associative, i.e. x + y + z Weblog, blogs.sun.com is interpreted as (x + y) + z, "First Steps to Scala", artima.com