What does the `#` operator mean in Scala? link Nested classes in scala are instance specific. To treat them at class level we access them with #:
trait if you define a trait it is like having an interface which defines its methods and can be in a multiple inheritance manner Similar to interfaces in Java, traits are used to define object types by specifying the signature of the supported methods. Unlike Java, Scala allows traits to be partially implemented; i.e. it is possible to define default implementations for some methods. In contrast to classes, traits may not have constructor parameters. abstract class Bird { def flyMessage: String def fly() = println(flyMessage) }Mixing in traits upon instantiation val pigeon = new Pigeon with Swimming pigeon.swim() yes, Serializable is an interface. but you use 'extends' for the first trait or the parent class, and 'with' only for additional traits Java Heap size memory: expoer JAVA_OPTS="-Xmx1024m -Xms256m"
Scala IDE info http://markup.su/highlighter/ Programming Scala - O'Rielly www.pastie.com Scala API Doc FREE ebook on scala: Programming in Scala On sbt, scala and scalaTest Quick start Scala/MongoDB $ git pull $ sbt eclipse $ git add ./abc/file.txt $ git commit -m "commit message" $ git push A multi-line string literal is a sequence of characters enclosed in triple quotes """ ... """. The null value is of type scala.Null, and is thus compatible with every reference type. It denotes a reference value which refers to a special "null" object. Define Variables var myVar : String = "Foo" //variable val myVal : String = "Foo" //immutable - constant Scala supports multiple assignment. If a code block or method returns a Tuple, the Tuple can be assigned to a val variable. val (myVar1: Int, myVar2: String) = Pair(40, "Foo") If you have a reference to the object from outside the method. Method parameters are always mutable and defined by val keyword. Access Modifierprivate: Java would permit both accesses because it lets an outer class access private members of its inner classes. protected: only accessible from subclasses of the class in which the member is defined. public Modify access scope package society { package professional { class Executive { private[professional] var workDetails = null private[society] var friends = null private[this] var secrets = null def help(another : Executive) { println(another.workDetails) println(another.secrets) //ERROR } } } } Variable workDetails will be accessible to any class within the enclosing package professional. Variable friends will be accessible to any class within the enclosing package society. Variable secrets will be accessible only on the implicit object within instance methods (this). Loops// nested for loop
var a = 0; val numList = List(1,2,3,4,5,6,7,8,9,10); // for loop execution for( a <- numList if a != 3; if a < 8 ){ println( "Value of a: " + a ); } Yield (Get index range) var a = 0; val numList = List(1,2,3,4,5,6,7,8,9,10); // for loop execution with a yield var retVal = for{ a <- numList if a != 3; if a < 8 }yield a //for loop with no body and a yield // Now print returned values using another loop. for( a <- retVal){ println( "Value of a: " + a ); } FunctionsScala function's name can have characters like +, ++, ~, &,-, -- , \, /, : etc. Parameter call by name parameter a call-by-name parameter by putting the => symbol between the variable name and the type object Test { def main(args: Array[String]) { delayed(time()); // first goes to the delayed method and it won't evaluate parameter ntil it is required } //unlike java where parameters have early evaluation. def time() = { println("Getting time in nano seconds") System.nanoTime } def delayed( t: => Long ) = { println("In delayed method") println("Param: " + t) t } } In delayed method Getting time in nano seconds Param: 105771974498462 Getting time in nano seconds last parameter to a function may be repeated. This allows clients to pass variable length argument lists to the function. Currying transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. Curried functions are defined with multiple parameter lists, as follows: def strcat(s1: String)(s2: String) = s1 + s2 Alternatively, you can also use the following syntax to define a curried function: def strcat(s1: String) = (s2: String) => s1 + s2Following is the syntax to call a curried function: strcat("foo")("bar") Lists, Streams: Seq
scala> Stream.cons(1, Stream.cons(2, Stream.empty)) === cons(1, cons(2, empty)) ==== 1 #:: 2 #:: empty //st1: Stream.Cons[Int] = Stream(1, ?) //1, 2 scala> def numsFrom (n :Int):Stream[Int] = Stream.cons(n,numsFrom (n+1)) //kinda w/ same meaning as Stream.cons.apply scala> numsFrom(0) scala> n take 10 print // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, empty EQUIVALENT TO scala> def numsFrom(start: Int): Stream[Int] = start #:: numsFrom(start + 1) scala> println(f.take(10).mkString(",")) // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, empty Remove items from Stream f.drop(5) //remove first n items and return a new stream. Filter on Streams scala> val even = f filter (_ % 2 == 0) scala> even take 10 print // 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, empty // Now the first 19 elements of the natural number’s Stream has been initialized: scala> println(f) //Stream(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, ?) Pattern Matching on Streams scala> f match{case 0 #:: 1 #:: _ => println("matched")} //matched if the stream starts with 0,1. The trailing _underscore_ says that we are not interested in the remaining elements. Infinite Stream in Exception scala> f.sum OpenJDK Server VM warning: Exception java.lang.OutOfMemoryError occurred dispatching signal SIGINT to handler- the VM may need to be forcibly terminated A Stream can be used like every other collection because it is of type LinearSeq. Operations like filter and map are lazy evalutated. They simply return another Stream and perform the operation when required. I think we can say that all operations that return another Stream can be considered as lazy operations (like filter, map). Of course, operations like foldLeft, foldRight, find and exists are not lazy. Stream is the immutable equivalent to Iterator. While an Iterator doesn’t keep computated values Stream does. So as with any immutable data structure you don’t have to care about state with Streams. This is useful when you pass a Stream around to other functions. If you do so with a Iterator you have to care about state what needs much more caution and can lead to logic errors. The immutability of Streams makes it also quite easy to compose them. Keep in mind that a Stream has a higher memory footprint than an Iterator because it keeps the computed elements. The only mutable collection. Scala has maps and sets that are mutable but should be used if there are performance issues with immutable maps/sets. var z:Array[String] = new Array[String](3) OR var z = new Array[String](3) //an array that can hold up to 3 elements z(0) = "Zara"; z(1) = "Nuha"; z(4/2) = "Ayan" OR var z = Array("Zara", "Nuha", "Ayan") Multi-dimentional Array var myMatrix = ofDim[Int](3,3) //an array with three elements each of which is an array with three elements for (i <- 0 to 2) { for ( j <- 0 to 2) { myMatrix(i)(j) = j; } } var myList1 = Array(1.9, 2.9, 3.4, 3.5) var myList2 = Array(8.9, 7.9, 0.4, 1.5) var myList3 = concat( myList1, myList2) var myList1 = range(10, 20, 2) //from 10 to 20 step is 2 Linked list, elements are not repalceable like arrays (immutable) Initialize val a: List[String] = List("apples", "oranges", "pears") // List of Strings val a: List[Nothing] = List() // Empty List. val a: List = List.fill(3)("apples") // Repeats apples three times. ls.foreach( e => println(e.toUpperCase) ) val a: List[List[Int]] = List( List(1, 0, 0), List(0, 1, 0), List(0, 0, 1)) // Two dimensional list Concatenate scala.collection.immutable.List val a = List(1,2,3) val b = List(4,5,6) a ::: b // List(1, 2, 3, 4, 5, 6) OR a.:::(b) // List(9, 5, 7, 1, 2, 3) use two lists with Set.:::() method OR List.concat(a, b) OR a ++ b ! val a = List(1,2,3); val b = 0 :: a a: List[Int] = List(1, 2, 3) b: List[Int] = List(0, 1, 2, 3) ! (System.identityHashCode(a), System.identityHashCode(b.tail)) (Int, Int) = (4434504,4434504) the tail of b *IS* a … no copying Other Methods a.head a.tail a.isEmpty a.reverse def apply(n: Int): A // Selects an element by its index in the list. Note: may take time die to the index value. def map[B](f: (A) => B): List[B] // Builds a new collection by applying a function to all elements of this list. def dropRight(n: Int): List[A] //Returns all elements except last n ones. def forall(p: (A) => Boolean): Boolean //Tests whether a predicate holds for all elements of the list. def filter(p: (A) => Boolean): List[A] //Returns all elements of the list which satisfy a predicate. reduceLeft((a, b) => a + b) //Applies a binary operator to all elements of this list, going left to right. reduceLeft(_+_) cons All lists can be defined using two fundamental building blocks, a tail Nil and :: which is pronounced cons. Nil also represents the empty list. All the above lists can be defined as follows: val fruit = "apples" :: ("oranges" :: ("pears" :: Nil)) val nums = 1 :: (2 :: (3 :: (4 :: Nil))) // Empty List. val empty = Nil // Two dimensional list val dim = (1 :: (0 :: (0 :: Nil))) :: (0 :: (1 :: (0 :: Nil))) :: (0 :: (0 :: (1 :: Nil))) :: Nil def foreach(f: (A) => Unit): Unit // Applies a function f to all elements of the list Flatten scala> val foo = List(List(1), List("a"), List(2.3)) //foo: List[List[Any]] = List(List(1), List(a), List(2.3)) scala> List.flatten(foo) // List[Any] = List(1, a, 2.3) mapsval a:Map[Char,Int] = Map() // Empty hash table whose keys are strings and values are integers: val a = Map("USA" -> "Washignton", "France" -> "Parice") // A map with keys and values. a += ("Germany" -> "Berlin") //add an element a.keys a.values a.isEmpty map1 ++ map2 //concat map1.++(map2) //concat ++ as method name a.keys.foreach{ myKey => print( "Key = " + myKey ) println(" Value = " + a(myKey) )} Pattern Matching
Other underscore uses def foo(l: List[Option[_]]) = ... //existential types case class A[K[_],T](a: K[T]) //higher kinded type parameters val _ = 5 //Ignored variables List(1, 2, 3) foreach { _ => println("Hi") } //Ignored parameters Some(5) match { case Some(_) => println("Yes") } //Wildcard patterns import java.util._ //Wildcard imports import java.util.{ArrayList => _, _} //Hiding imports def bang_!(x: Int) = 5 ///Joining letters to punctuation def foo_=(x: Int) { ... } //Assignment operators List(1, 2, 3) map (_ + 2) //Placeholder syntax List(1, 2, 3) foreach println _ //Partially applied functions NothingNull, null: Null is a trait, which (if you’re not familiar with traits) is sort of
like an abstract class in Java. There exists exactly one instance of
Null, and that is null. The literal null serves the same purpose as it does in Java. It is the
value of a reference that is not refering to any object. So if you
write a method that takes a parameter of type Null, you can only pass in
two things: null itself or a reference of type Null. scala> def tryit(thing: Null): Unit = { println( "That worked!" ); } tryit: (Null)Unit scala> tryit( "hey" ) <console>: 6 : error: type mismatch; found : java.lang.String( "hey" ) required: Null tryit( "hey" ) ^ scala> val someRef: String = null someRef: String = null scala> tryit(someRef) <console>: 7 : error: type mismatch; // It’s a null reference to a String. It may be null at run-time, but compile-time type checking says this is a no-no. found : String required: Null tryit(someRef) ^ scala> tryit(null) That worked! scala> val nullRef: Null = null nullRef: Null = null scala> tryit(nullRef) That worked! Nil: Empty list scala> Nil res4: Nil.type = List() scala> Nil.length res5: Int = 0 scala> Nil + "ABC" res6: List[java.lang. String ] = List( ABC ) scala> Nil + Nil res7: List[object Nil] = List(List()) See? It’s basically a constant encapsulating an empty list of anything. It’s has zero length. It doesn’t really represent ‘nothingness’ at all. It’s a thing, a List. There are just no contents. Nothing: If any of these is a little difficult to get, it’s Nothing. Nothing is another trait. It extends class Any. Any is the root type of the entire Scala type system. An Any can refer to object types as well as values such as plain old integers or doubles. There are no instances of Nothing, but (here’s the tricky bit) Nothing is a subtype of everything. Nothing is a subtype of List, it’s a subtype of String, it’s a subtype of Int, it’s a subtype of YourOwnCustomClass. Remember Nil? It’s a List[Nothing] and it’s empty. Since Nothing is a subtype of everything, Nil can be used as an empty List of Strings, an empty List of Ints, an empty List of Any. So Nothing is useful for defining base cases for collections or other classes that take type parameters. Here’s a snippet of a scala session: scala> val emptyStringList: List[String] = List[Nothing]() emptyStringList: List[String] = List() scala> val emptyIntList: List[Int] = List[Nothing]() emptyIntList: List[Int] = List() scala> val emptyStringList: List[String] = List[Nothing]("abc") <console>:4: error: type mismatch; found : java.lang.String("abc") required: Nothing val emptyStringList: List[String] = List[Nothing]("abc") None: When you’re writing a function in Java and run into a situation where you don’t have a useful value to return, what do you do? There are a few ways to handle it. You could return null, but this causes problems. If the caller isn’t expecting to get a null, he could be faced with a NullPointerException when he tries to use it, or else the caller must check for null. Some functions will definitely never return null, but some may. As a caller, you don’t know. There is a way to declare in the function signature that you might not be able to return a good value, the throws keyword. But there is a cost associated with try/catch blocks, and you usually want to reserve the use of exceptions for truly exceptional situations, not just to signify an ordinary no-result situation. Scala has a built-in solution to this problem. If you want to return a String, for example, but you know that you may not be able to return a sensible value you can return an Option[String]. Here’s a simple example. scala> def getAStringMaybe(num: Int): Option[String] = { | if ( num >= 0 ) Some("A positive number!") | else None // A number less than 0? Impossible! | } getAStringMaybe: (Int)Option[String] scala> def printResult(num: Int) = { | getAStringMaybe(num) match { | case Some(str) => println(str) | case None => println("No string!") | } | } printResult: (Int)Unit scala> printResult(100) A positive number! scala> printResult(-50) No string! Unit: This is another easy one. Unit is the type of a method that doesn’t return a value of any sort. Sound familiar? It’s like a void return type in Java. Here’s an example: scala> def doThreeTimes(fn: (Int) => Unit) = { | fn(1); fn(2); fn(3); | } doThreeTimes: ((Int) => Unit)Unit scala> doThreeTimes(println) 1 2 3 scala> def specialPrint(num: Int) = { | println(">>>" + num + "<<<") | } specialPrint: (Int)Unit scala> doThreeTimes(specialPrint) >>>1<<< >>>2<<< >>>3<<< apply
So basically, Lazy
Infosbt is the standard build tool for Scala projects, has plug-ins that can generate Eclipse project files out of the sbt project definition.Scala compiles to Java bytecode, meaning it runs on the JVM. A function is given a set of inputs, a function should always return the same output. every function must return a value, but that functions must inherently carry no intrinsic state from one call to the next. stateless Scala is statically typed,immutable objects by default heavy use of type inferencing Scala does not require the semicolon, termination is obvious by the line ending Scala does not require the file containing a class definition to mirror the name of the class Code Example (MyHello.scala)object HelloWorld { //singleton pattern: instance is created on demand, the first time it is used. /** define a function and assign it to a variable, (Unit is equivalent to void in java) */ def main(args: Array[String]): Unit = { // name : type System.out.println("Hello, Scala!") } } $ scalac Hello.scala $ scala HelloWorld OR java -classpath %SCALA_HOME%\lib\scala-library.jar;. HelloWorld System.out.println demonstrates Scala's fidelity to the underlying Java platform. Scala make the full power of the Java platform available to Scala programs. (it will even allow a Scala type to inherit from a Java class, and vice versa) Object: denotes singleton pattern, therefore main is not defined static. static members (methods or fields) do not exist in Scala. Rather than defining static members, the Scala programmer declares these members in singleton objects. a Scala application will allow both a class definition and an object definition of the same name. Scala uses square brackets ("[]") instead of angle brackets ("<>") to indicate parameterized types
Threads
run shell commands (Scala ProcessBuilder)use Scala's sys.process library: scala> import sys.process._ import sys.process._ scala> "ls /home/dcs/scala-2.9.1.final".! bin doc lib man meta misc src res1: Int = 0 Other hints https://www.google.com/search?client=ubuntu&channel=fs&q=scalaz&ie=utf-8&oe=utf-8 <adelbertc> val validFiles = myFiles.filter(filepath => filepath.size <= 10) <tnks> you could follow with a .toVector or something like that to get a strict collection with the results ! Stream(Some(1), None, Some(2), None, None).flatten.toList // mor8a <luft> ok, how do I check if A <:< object x when A <: AnyRef : ClassTag? <multibot_> List[Int] = List(1, 2) <tpolecat> ! Stream(Some(123), None, Some(456), None, None).flatten.mkString <multibot_> String = 123456 <Naktibalda> you never need a for loop in scala <tpolecat> mor8a: no, explicit looping is very rare in scala <_pa_> Naktibalda: depends on what you mean <_pa_> for (x <- xs) bar(x) <_pa_> Is that a for loop? =) <dfrey> _pa_: Wouldn't you just do this though? xs.foreach(bar) <ecuderpam> dfrey: The for-comprehension desugars to something like that. <_pa_> dfrey: they're equivalent <dfrey> _pa_: They are equivalent yes, but isn't it preferred to use foreach for simple cases? <_pa_> By whom? <_pa_> I find that the for comprehension often cleans things up <ecuderpam> the passive voice is said to prefer X <qu1j0t3> ecuderpam: Experts agree <d_m_> dfrey: just preferences. i like foreach better personally. <_pa_> When you have more than one monadic operation after installing scala you can just start coding! $ scala scala> 2+3 res0: Int = 5 scala> "hello" + res0 //access to previous temp variables res1: java.lang.String = hello5 scala> res2.to //click tab for auto complete scala>res2.toUpperCase //no parenthesis needed JsonTo parse a json file.
TODO read: functional features (such as pattern matching) operator overloading generics with "upper and lower type bounds," views Strategy pattern Promises (Futures) A typical future looks like this:
Or with the more idiomatic:
Both code snippets delegate the execution of fatMatrix.inverse() to an ExecutionContext and embody the result of the computation in inverseFuture |