Tuesday, 20 October 2015

Scala Features

1. Evaluation rules

def example = 2 // evaluated when called
val example = 2 // evaluated immediatelly
lazy val example = 2 // evaluated once when needed

//call by value, evaluates the arguments before calling the function
def square(x: Double)

// call by name, evaluates the function first, then evaluates the arguments if needed
def quare(x:=> Double)

2. Higher order functions
Take a function as a parameter or return functions

def sum(f: Int => Int):(Int, Int)=>Int = {
    def sumf(a: Int, b: Int): Int = {}

3. Currying

Converting a function with multiple arguments into a function with a single function, which returns another function.

def f(a: Int)(b: Int): Int

4. Traits are similar to Java interfaces, except they can have non-abstract members.

scala.Any: base type of all types. Has methods hasCode and toString that can be overridden.

scala.AnyVal: base type of all primitive types. scala.Double, etc.

scala.AnyRef: base type of all reference types. scala.List, any user-defined class

scala.Nothing is subtype of any other type without any instance.

5. Type parameters

Type parameters can apply to classes, traits or functions.

// T must derive from Toplevel or be Toplevel
def myFct[T <: Toplevel](arg: T): T = {}
// T must be a supertype of Level1
def myFct[T >: Level1](arg: T): T = {}

6. Variance

Given A <: B, if C[A] <: C[B], C is covariant;
If C[A] >: C[B], C is contravariant, otherwise C is nonvariant

class C[+A] // C is covariant
class C[-A] // C is contravariant
class C[A] // C is nonvariant

7. Translation Rules

for (x<- e1) yield e2 <---> e1.map(x => e2)
for (x <- e1 if f) yield e2 <--> for (x <- e1.filter(x =>f)) yield e2

(1 until n).flatMap(i => (1 until i).filter(j => isPrime(i+j)).map(j => (i,j)))

No comments:

Post a Comment