My Scala Cheat Sheet

Constructing a empty List
for the following:
def aMethod[A](a:A):List[A] =
this works:
1.  a :: Nil
2.  a :: List()
3.  a :: List.empty[A]
but for:
def my2[A,B](a:List[A], f: A => B):List[B]=a.foldRight(initalvalue)((x,y) => f(x)::y)
initalvalue needs explicit type annotation
so only number 3 from above works or casting like this: Nil:List[A]
Iterating over a list of tuples,  Extractor on tuples
val tups=List((1,2),(4,5),(8,9))
tups.foreach { case (s, i) => println(s + i) }
for { tup <- tups; (a, b) = tup } yield a + b

filter a collection based using pattern matching in a for comprehension

abstract class Base
case class CaseA(s: String) extends Base
case class CaseB(i: Int) extends Base

val xs: List[Base] = List(CaseA("foo"), CaseB(123), CaseB(456), CaseA("bar"))

for (x @ (xx: CaseA) <- xs) {println(x)}

filter a [Option] collection
 val results = List(Some("apple"), None, Some("orange"))
 for(Some(r) <- results)println(r)
or
for{ r <- results; sr <- r}yield(new String(sr))

Tuples
productElement
productArity

Imports
import some.package.{method => _,_ }
removes import from Program -> Predef


Partial function application
def add(a:Int, b:Int) = a + b

scala> val f: (Int) => Int = (a) => add(1,a)
f: Int => Int = <function1>

scala> val f2= add(1, _:Int)
f2: Int => Int = <function1>

scala> val f3 = (a:Int) => add(1,a)
f3: Int => Int = <function1>


Multiline Functions
Wrap in {}

for {
gen <- collection
gen2 <- gen.gen2


}println()





TODO
type lambdas, specialization and...