View composeFutureOfNullable.kt
@Test
fun combineNullable() {
fun giveInt(x: Int):Int? = x+1
fun giveInt2(x: Int):Int? = x+2
fun combine(x: Int): Int? = giveInt(x)?.let { giveInt2(it) }
assertEquals(combine(1),4)
}
View optionalFlatten.md

How to retrieve List("a", "b") from a list of optional values

A very common use case when dealing with options...

Scala

val values = List(Some("a"), None, Some("b")).flatten

Java

View observe.js
var names = ['joe', 'bob'];
Object.observe(names, function(changes){
changes.forEach(function(change) {
console.log(change.type, change.name)
});
console.log("names",names);
});
View ConstructorDI.scala
class PrintService {
def print = println("I'm a real service")
}
trait Services {
val printService = new PrintService()
// put your other services here
}
//for example, a Play controller
View futureError.scala
val f: Future[Int] = Future {
if(math.random < 0.5) 1 else throw new Exception("Oh no")
} recover {
case ex:Exception => {
println(ex.getMessage)
-1
}
}
f map println
View xmlParsing.scala
//val xmlNode = xml.XML.loadFile("xxx")
val xmlNode =
<persons>
<person age="30">
<name>bob</name>
</person>
<person age="40">
<name>joe</name>
</person>
View streamFile.md

Chunck by chunk

def  transform = Action {
    
     val fileStream: Enumerator[Array[Byte]] = {
         Enumerator.fromFile(new File("data.txt"))
     }
     
     val transfo = Enumeratee.map[Array[Byte]]{byteArray =>  
View TypeClassExample.scala
scala> List(1,2,3).sum
res0: Int = 6
scala> case class Color(name: String)
defined class Color
scala> List(Color("red"), Color("blue"), Color("Yellow")).sum
View patternMatch.md

Scala pattern matching example

Value matching

def f(x: Int): String = x match {
  case 1 | 2 => "one or two"
  case 3 => "three"
  case _ => "other values"
}
View printToFile.md

Higher order function to write stuffs in a file, with automatic resources management

Code

  def printToFile(f: java.io.File)(op: java.io.PrintWriter => Unit) {
    val p = new java.io.PrintWriter(f)
    try { op(p) } finally { p.close() }
  }