
Symbolics Operators Import import java.awt._ // All classes under java.awt -> Returns a two-element Map( 1 -> "A", 2 -> "B") +, -, *, /, % Arithmetics import java.io.File tuple containing the key (1).->(“A”) >, < ,<=, >=, ==, != Relational import java.io.File._ // Import all Fileʼ static methods and value &&, ||, ! Logical import java.util.{Map, HashMap} // only the 2 classes _ A placeholder, used in import com.xtech._ imports, function literals, &, |, ^, ~ Bitwise Narrow import: case _ => value.toString (and, or, xor, inv) etc. numbers.filter(_ < 0) def doIt() = { <<, >>, >>> Bitwise shift import java.math.BigDecimal.{ONE} : Separator between def add(i: Int): Int = ... (left, right, unsigned right) identifiers and type println(ONE) annotations. } The operator “==” check the value equality on = Assignment. val one = “1” reference AND primitive type. Rename import: import java.math.BigDecimal.{ ONE => _, ## // Exclude ONE => Used in function literals numbers.filter(x => x < 0) Rich Operation ZERO => JAVAZERO # // Rename it to separate the argument } ! list from the function Scala provides “rich wrapper” around basic types via implicit println(JAVAZERO) body. conversions. <- Used in for for (arg <- args) import statements are relative, not absolute. To " comprehensions in Code Result create an absolute path, start with _root_ generator expressions. 0 max 5 5 <: Upper bounds (a subtype def apply[T <: U](x: T) import _root_.scala.collectionsjcl._ of)Used in parameterized 0 min 5 0 and abstract type -2.7 abs 2.7 Packages declarations to constrain -2.7 round -3L the allowed types. File names don’t have to match the type names, 1.5 isInfinity false the package structure does not have to match the <% View bounds( apply def m [A <% B](args): R directory structure. So, you can define packages in implicit convertion).Used = ... (1.0 / 0) isInfinity true files independent of their “physical” location. in parameterized and 4 to 6 Range(4,5,6) abstract type declarations Traditional: to convert the type using "nick" capitalize “Nick” package com.xtech.scala view. "nicolas" drop 2 “colas” Nested: >: Lower bounds (supertype def append[U >: T](x: U) package com{ of)Used in parameterized = Literals and abstract type package scala { class A } declarations to constrain Integer package util { class B } } the allowed types. val dec = 31 Decimal Integer # Refer to a type val ic: MyClass#myType val hex = 0XFF Hexa Integer Tuples declaration nested in = ... another type val long = 31L Long (“l” or “L”) Are immutable and can contain different types of elements. @ Marks an annotation. @deprecated def bad() = val little: Short = 367 Short val nena = (99, "Luftballons",”1983”) ʻ Symbol val s = 'aSymbol val littler: Byte = 38 Byte println(nena._1) def doIt(r: Symbol) println(nena._2) .... println(nena(0)) (not same Type in list) doIt(s); print(s.name) Floating point val double = 1.2345 Double _ Usage Summary Curried functions If a method takes 0 or one parameter you can drop val e = 1.234e4 Double (“e” or “E”) the dot and parentheses when calling the function. val float = 1.234F Float (“f” or “F”) def twice(op: Double => Double) (x: Double) = op(op(x)) twice(_ + 1) (5) Character and String res8: Double = 7.0 Variables val aChar = ʻDʼ Char twice(x => x + 1)(5) // More verbose Immutable (Final) val unicode = ʼ\u0043ʼ Unicode Char Existential types val msg = "Hello, world!" val string = “string” String Labeling something that is unknown: val msg: String = "Hello, world!" val s = “”” itʼs “you” “”” Raw String ( It’s “you” ) class Marshaller[T] { def marshall(t:T) = {println(t)} } val big = new java.math.BigInteger("12345") new Marshaller[String] Mutable Special character res1: Marshaller[String] = Marshaller@7896b1b8 var greets = "Hello, world!" Literal Meaning res1.isInstanceOf[Marshaller[_]] var greets: String = "Hello, world!" res4: Boolean = true \n line feed (\u000A) Lazy initialization same as: (only on Immutable) \b backspace (\u0008) .isInstanceOf[T forSome {type T <: Marshaller[String]}] object Demo { \t tab (\u0009) Function literals lazy val x = { println("initializing x"); "done" } \f form feed (\u000C) } someNumbers.filter(_ > 0) \r carriage return (\u000D) Partially applied functions Basic Types \” double quote (\u0022) def sum(a: Int, b: Int, c: Int) = a + b + c Value Type Range \’ single quote (\u0027) val a = sum _ Byte 8-bit signed two’s complement integer \\ backslash (\u005C) a: (Int, Int, Int) => Int = <function> (-27 to 27 - 1, inclusive) val b = sum(1, _: Int, 3) Boolean Short 16-bit signed two’s complement integer b: (Int) => Int = <function> (-215 to 215 - 1, inclusive) val bool = true Boolean (true | false) b(2) Int 32-bit signed two’s complement integer Check res10: Int = 6 (-231 to 231 - 1, inclusive) “abc”.isInstanceOf[String] Import statements Long 64-bit signed two’s complement integer (-263 to 263 - 1, inclusive) re0: Boolean = true import com.xtech.cf._ Char 16-bit unsigned Unicode character Cast Match expressions (0 to 216 - 1, inclusive) 3.asInstanceOf[Double] case _ => “default value” // Default case value String a sequence of Chars res0: Double = 3.0 Initialization Float 32-bit IEEE 754 single-precision float Runtime Representation Double 64-bit IEEE 754 double-precision float var age: Int = _ // age initialized to 0 Boolean true or false classOf[String] Setter res7: java.lang.Class[String] = class java.lang.String Redefined a setter method: def age_ = (a: Int) { if(girl) age = a - 5 else age = a } [email protected]!!!!!!1 / 6!! ! ! ! ! ! v. 1.1 Class Hierachy Variance Actors Covariance: Ability to accept sub-classes. import scala.actors._ Any “T <: Pet” or “+T” : (as T extends Pet) object SimpleActor extends Actor { Equivalent to def act() { java.long.Object Contra-variance: Ability to accept base classes “T >: Cat” or “-T” : (as T is superType of Cat) for (i <- 1 to 5) { AnyVal AnyRef println("Do it!") Traits Thread.sleep(1000) } A traits is like a java interface at the difference that it’s Unit Double ScalaObject possible to implements methods and fields on it. Traits can } be reused into classes by mixing the trait to the class or by } extending it. All java.* All scala.* Boolean Float To Start it: ref. types ref. types Definition SimpleActor.start() trait Saxo { def play() { To start a thread immediately use the utility method actor: import scala.actors._ println("Nice sound!") val seriousActor2 = actor { } for (i <- 1 to 5) Helper for type } Null inference println("Do it!.") Extends } Nothing class Alto extends Saxo { override def toString = "Alto" Send message to Actor; import scala.actors._ } Definition val echoActor = actor { With while (true) { Simple class: class Instrument receive { class ChecksumAccumulator { class Baryton extends Instrument { case msg => println("received message: "+ msg) private var sum = 0 override def toString = "Baryton" } def add(b: Byte): Unit = sum += b } } def checksum(): Int = ~(sum & 0xFF) + 1 val baryton = new Baryton() with Saxo } } Ordered Traits To send a message: Constructor echoActor ! “Hello” The Ordered trait defines <, >, <=, and >= just by received message: hi there The default constructor (primary constructor) is defined by implementing one method, compare. the body class and parameters are listed after the class class Rational(n: Int, d: Int) extends Ordered[Rational]{ To use the current thread use self: name. Other constructors (auxiliary constructor) are defined // ... self ! "hello" by the function definition “this()”: def compare(that: Rational) = self.receive { case x => x } class Rational(n: Int, d: Int) { (this.numer * that.denom) - (that.numer * this.denom) res6: Any = hello require(d != 0) } self.receiveWithin(1000) { case x => x } res7: Any = TIMEOUT val numer: Int = n Mixing val denom: Int = d Change Scheduler: def this(n: Int) = this(n, 1) // auxiliary constructor Once a trait is mixed into a class, you can alternatively call it } a mixin.Traits are a way to inherit from multiple class-like Run it on the main Thread constructs, but they differ in important ways from the trait SingleThread extends Actor{ To hide the constructor make it private: multiple inheritance present in many languages. With traits, override protected def scheduler() = class Rational private(n: Int, d: Int) the method called is determined by a linearization of the ## new SingleThreadScheduler classes and traits that are mixed into a class. } Getter / Setter Linearization algorithm Run all actors in the Main thread: Once a val or var is defined within a class the corresponding Scheduler.impl = new SingleThreadScheduler accessor methods are generated. The generated methods 1 Put the actual type of the instance as the first element. use the same privilege as the field. Thread reuse Only the getter is generated in case of val. 2 Starting with the right most parent type and working The methods don’t follow the JavaBean nomenclature. left,compute the linearization of each type, appending Writing an actor to use react instead of receive is its linearization to the cumulative linearization. (Ignore challenging, but pays off in performance. Because react To generate JavaBean getter and setter add the annotation: ScalaObject, AnyRef, and Any for now.) does not return, the calling actor’s call stack can be @scala.reflect.BeanProperty var level: Int = _ discarded, freeing up the thread’s resources for a different actor. At the extreme, if all of the actors of a program use Abstract 3 Working from left to right, remove any type if it react, then they can be implemented on a single thread. abstract class Document { appears again to the right of the current position. As empiric rule: def footNotes: Array[String] // abstract method 4 Append ScalaObject, AnyRef, and Any. - Actors that are message-heavy are better implemented var nbOfPages : Int // abstract Field class C1 {def m = List("C1")} with “while(true)/receive” (Hogging a thread). - Actors with non trivial work are better implemented with type paper# // abstract type trait T1 extends C1 {override def m ={ "T1" :: super.m}} } “loop/react”.
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages6 Page
-
File Size-