Listings for "Scala on the Java Virtual Machine," Java Magazine, Premiere Issue.

Listing 1

scala> val a = new java.util.ArrayList[Int]
a: java.util.ArrayList[Int] = []

scala> a.add(1)
res0: Boolean = true

scala> a add 2 
res1: Boolean = true 
scala> a 
res2: java.util.ArrayList[Int] = [1, 2]

Listing 2

scala> import scala.collection._ 
scala> val ab = mutable.ArrayBuffer.empty[Int] 
ab: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer() 
scala> ab += 5
res14: ab.type = ArrayBuffer(5) 
scala> ab.+=(7) 
res15: ab.type = ArrayBuffer(5, 7) 

Listing 3

abstract class Amphibian {
    def color: String
    def swims = true
    def breathes = true
}
trait Green {
    def color = "Green"
}
trait HasLegs {
    def legs: Int
    def move = println("I move using %d legs".format(legs))
}
class Frog extends Amphibian with Green with HasLegs {
    val legs = 4
}

Listing 4

scala> import scala.reflect.Manifest 
scala> def typeOf[T](obj: T)(implicit m: Manifest[T]) = {
     |   println("%s is of type %s".format(obj, m.erasure)) 
     | } 
typeOf: [T](obj: T)(implicit m: scala.reflect.Manifest[T])Unit 
scala> typeOf(6)
6 is of type int 
scala> typeOf(6.1) 
6.1 is of type double 
scala> typeOf("hello") 
hello is of type class java.lang.String

Listing 5

scala> def sumItUp(list: List[Any]): Int = list match {
     |   case listOfInts: List[Int] => listOfInts.sum
     |   case listOfStrings: List[String] =>
     |                 listOfStrings.map(_.toInt).sum 
     |   case _ => 0 
     | } 
warning: there were unchecked warnings; re-run with -unchecked for details 
scala> sumItUp(List(1,2,3)) 
res8: Int = 6 
scala> sumItUp(List("1","2","3")) 
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer 

Listing 6

scala> def sumItUp(list: List[Any]): Int = list match {
     |   case listOfThings: List[_] => listOfThings.map { 
     |       case i: Int => i 
     |       case s: String => s.toInt 
     |       case _ => 0 
     |     }.sum 
     |   case _ => 0 
     | } 

scala> sumItUp(List(1,2,3))
res10: Int = 6 
scala> sumItUp(List("1", "2", "3")) 
res11: Int = 6 
scala> sumItUp(List("1", 2, "3"))  
res12: Int = 6 

©2011, Oracle Corp.