187x Filetype PDF File size 0.11 MB Source: www.ecb.torontomu.ca
COE 808 Tue. March 2, 2010 Scala Page 1 of 3 COE808 Lecture Notes Tuesday March 2, 2010 Topics • Scala Scala Scala goals Ref: Scala overview • Both object-oriented and functional programming paradigms supported. • Scalable (from small to large software systems) component re-use a major goal. • Works well with Java and C#. • Uniformity: every value is an object (no distinction between primitive and reference data types as in Java) and every operation is a method call (similar to scheme) • Every class inherits from Scala.Any. Value classes (roughly like Java's primitives) inherit from Scala.AnyVal and all reference classes inherit from Scala.AnyRef. • Equality (==) works like .equals(Object o) in Java; the scala .eq() method (which cannot be overridden) checks for true identity in the rare cases when this is needed (eg. Implementing hash tables). • Operators (like +) are methods. Indeed an identifier between two variables is treated as a method call. Thus val a = 3; val b = 4; println(a.+(b)); is how a+b is interpreted. Similarly, “abcd”.contains(“bc”) (which returns True) can be written as “abcd” contains “bc”. • Examples object PrintOptions { def main(args: Array[String]): Unit = { System.out.println("Options selected:") for (arg <- args) if (arg.startsWith("-")) System.out.println(" "+arg.substring(1)) } } object PrintArgs { COE 808 Tue. March 2, 2010 Scala Page 2 of 3 def main(args: Array[String]): Unit = { //Anonymous function (params => body of anonymous function) args.foreach(arg => println(arg)) } } class Celsius { private var d: Int = 0 def degree: Int = d def degree_=(x: Int): Unit = if (x >= -273) d = x } object Timer { var i = 0 def oncePerSec(callback: () => Unit) { while(true) {callback(); Thread sleep 1000 } } def timeFlies() { println("Time flies like an arrow " + i) i += 1 } def main(args: Array[String]) { oncePerSec(timeFlies) } } class Complex(real: Double, imag: Double) { def re = real def im = imag override def toString() = "" + real + (if (imag < 0) "" else "+") + imag + "i" def add(z: Complex): Complex = new Complex(this.re + z.re, im + z.im) //OR define the + operator def +(z: Complex) = new Complex(this.re + z.re, im + z.im) def *(z: Complex) = new Complex(re * z.re - im*z.im, im*z.re + z.im*re) } import java.util.{Date, Locale} import java.text.DateFormat import java.text.DateFormat._ object FrenchDate { COE 808 Tue. March 2, 2010 Scala Page 3 of 3 def main(args: Array[String]) { val now = new Date val df = getDateInstance(LONG, Locale.FRANCE) println(df format now) } }
no reviews yet
Please Login to review.