Scala

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.

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

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 Modifier

private: 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

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).

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.

Array

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.

a.heada.taila.isEmptya.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:

Pattern Matching

defmatchTest(x:Int):String=xmatch{case1=>"one"case2=>"two"case_=>"anything else"}expr match {
case List(1,_,_) => " a list with three element and the first element is 1"
case List(_*) => " a list with zero or more elements "
case Map[_,_] => " matches a map with any key type and any value type "
case _ =>
}

In scala, _ acts similar to * in java while importing packages.

importscala.util.matching._// imports all the classes in the package matchingimportcom.test.Fun._// imports all the members of the object Fun. (static import in java)importcom.test.Fun.{Foo=>Bar,_}// imports all the members of the object Fun but renames Foo to Barimportcom.test.Fun.{Foo=>_,_}// imports all the members except Foo. To exclude a member rename it to _

//assign a function to a new variableclassTest{deffun={// some code}valfunLike=fun_}

Nothing

Null, 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> deftryit(thing: Null): Unit ={ println("That worked!"); }

tryit: (Null)Unit

scala> tryit("hey")

<console>:6: error: typemismatch;

found : java.lang.String("hey")

required: Null

tryit("hey")

^

scala> val someRef: String =null

someRef: String =null

scala> tryit(someRef)

<console>:7: error: typemismatch; // 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:

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.

Info

sbt 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.

statelessimmutable objects by default

Scala is statically typed,

heavy use of type inferencing

Scala does not require the semicolon, termination is obvious by the line endingScala 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 ﬁrst 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!") }}

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 ﬁelds) do not exist in Scala. Rather than deﬁning 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.

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