Build scala and scala API docs from source

1. Install Java 8
2. Install apache ant:

brew install ant

3. Check out the scala repo:

git clone https://github.com/scala/scala.git

4. Build the scala distribution with

ant

Wait 16 minutes.

5. Build the scala docs with:

ant docs

Wait 6 minutes.

Get current directory in scala

This just uses one of the Java utilities to get the current directory (this property is where Java was run from).

def pwd = System.getProperty("user.dir")

Example:

scala> println(pwd)
D:\Program Files (x86)\Git

Scala getOrElse example

The “getOrElse” function in Scala is a feature designed to help write code that avoids NullPointerExceptions.

scala> val x = null
x: Null = null
 
scala> x.toString
java.lang.NullPointerException
  ... 33 elided

Null is there to be like Java, but generally “None” is used instead:

val x = None
val y = Some(107)

This is similar to Java:

Integer x = null;
Integer y = 107;

The difference is that in Scala, the language gives you some nice options.

List(None, Some(107)).
  map( x => x.getOrElse(-1) )
 
res54: List[Int] = List(-1, 107)

You could also use a function (e.g. to log a warning):

List(None, Some(107)).
  map( x => x.getOrElse( { println("error") } )

You can also do useful things to handle unimplemented APIs – if you are writing code and you’re not sure if a branch will ever be used, you can avoid it by marking it as not implemented, with this awesome syntax:

List(None, Some(107)).
  map( x => x.getOrElse(???))
 
scala.NotImplementedError: an implementation is missing
  at scala.Predef$.$qmark$qmark$qmark(Predef.scala:225)
  at $anonfun$1$$anonfun$apply$1.apply(<console>:10)
  at $anonfun$1$$anonfun$apply$1.apply(<console>:10)
  at scala.Option.getOrElse(Option.scala:120)
  at $anonfun$1.apply(<console>:10)
  at $anonfun$1.apply(<console>:10)
  at scala.collection.immutable.List.map(List.scala:272)
  ... 35 elided

Scala list comprehension

Scala offers list comprehensions, which are a simple way to create lists. These are often used to convert one list into another, while applying some change to each entry. List comprehensions can also filter a list.

For example, we can determine the length of words in a sentence:

val x = "The quick brown fox jumps over the lazy dog".split(" ")
y: Array[Int] = Array(3, 5, 5, 3, 5, 4, 3, 4, 3)

Then, we can filter it to only long words:

val z = for (i <- x if i.length > 4) yield i 
z: Array[String] = Array(quick, brown, jumps)

Let’s say we had a second sentence, and we wanted to find the words that are in both.

We can do this with a for comprehension:

For instance:

val words1 = "This is an example sentence about a lazy dog".split(" ")
val words2 = "The quick brown fox jumps over the lazy dog".split(" ")
 
for (
  i <- words1;
  j <- words2 if i.equals(j)
) yield i
 
res22: Array[String] = Array(lazy, dog)

It’s worth noting that you can also use a numeric range:
You can also use a numeric range:

for (i <- 0 to 5) yield i
 
res11: scala.collection.immutable.IndexedSeq[Int] = 
  Vector(0, 1, 2, 3, 4, 5)

Scala main

Scala has a simple way of creating a ‘main’ method:

object HelloWorld { 
  def main(args: Array[String]) { 
    println("Hello, world!")
  } 
}

This will compile down to the “public static void main” that Java uses.

Alternately, you can extend “App”:

object HelloWorld extends App {
  println("Hello World")
}

Note that the “main” part is done for you.

Also you must compile this, and not run it through the interpreter. I.e.:

scalac hello.scala
scala Hello
Hello World!

Scala sortWith example

The “sortWith” function lets you sort an array according to a specified rule.

To demonstrate this, let’s make a list of random numbers:

val x = 
  List.fill(20)(100)
      .map(scala.util.Random.nextInt)
 
x: List[Int] = 
  List(90, 13, 69, 46, 66, 
       86, 38, 18, 88, 26, 
       81, 18, 11, 74, 5, 
       50, 7, 42, 74, 57)

You can sort this like so:

x.sortWith(
  (a, b) => {
    a > b
  }
)

Note that you should never use “return” in scala.

The above code can be re-written more simply:

x.sortWith(
  (a, b) =>
    a > b
)

However, “a”, and “b” have no importance here. For simple implementations, you can use an underscore syntax,

x.sortWith(_ > _)

What this does is to create a comparison function that takes two arguments, and checks if the first is larger than the second – in this case the “_” is not a variable, but more of a placeholder syntax.

Fixing scala error: “error: return outside method definition”

If you are starting at Scala, and are accustomed to older languages, you may be tempted to sort a list like so:

val x = new List(3, 1, 2)
 
x.sortWith( 
  (a, b) => { 
    return a > b
  } 
)

This code will throw the following error:

error: return outside method definition

The intent of this code is to create the equivalent of a Java comparator, using an anonymous function. However, “return” is not defined correctly in Scala, and should never be used.

The above example can be rewritten like so:

val x = new List(3, 1, 2)
 
x.sortWith( 
  (a, b) => { 
    a > b
  } 
)

This implicitly returns a value from the function. The “return” keyword returns from a function that is tied to an object (a “method”), so if this code was inside a method it would “work”, but drop several stack frames.

Scala example “Hello World”

The scala programming language has become a popular replacement for Java.

Once you download scala, you can access it from the command line:

scala> Garys-MBP:search gary$ scala
Welcome to Scala version 2.11.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_25).
Type in expressions to have them evaluated.
Type :help for more information.

This is an excellent place to explore the language. For example, you can print to the screen:

scala> println("Hello World!")
Hello World!

To exit, press ctrl-C.

Now, let’s put some code in a file named hello.scala (you can also run this in the scala command line interpreter):

object HelloWorld { 
  def main(args: Array[String]) { 
    println("Hello, world!")
  } 
}

On the command line, you can run this with the scala interpreter:

scala hello.scala 
Hello, world!

One of the benefits of using scala is the libraries that ship with the language.

For instance, let’s go back into the scala interpreter and make a list:

scala> val x = List(1, 2, 3)
x: List[Int] = List(1, 2, 3)

Now, type “x.” at the command line, and press tab twice: this will show you functions you can call on the list.

scala> x.
++             canEqual        drop        foreach           isDefinedAt          mapConserve    product             reverseMap      sorted         toIndexedSeq    unzip3         
++:            collect         dropRight   genericBuilder    isEmpty              max            productArity        reverse_:::     span           toIterable      updated        
+:             collectFirst    dropWhile   groupBy           isInstanceOf         maxBy          productElement      runWith         splitAt        toIterator      view           
/:             combinations    endsWith    grouped           isTraversableAgain   min            productIterator     sameElements    startsWith     toList          withFilter     
:+             companion       exists      hasDefiniteSize   iterator             minBy          productPrefix       scan            stringPrefix   toMap           zip            
::             compose         filter      head              last                 mkString       reduce              scanLeft        sum            toSeq           zipAll         
:::            contains        filterNot   headOption        lastIndexOf          nonEmpty       reduceLeft          scanRight       tail           toSet           zipWithIndex   
:\             containsSlice   find        indexOf           lastIndexOfSlice     orElse         reduceLeftOption    segmentLength   tails          toStream                       
addString      copyToArray     flatMap     indexOfSlice      lastIndexWhere       padTo          reduceOption        seq             take           toString                       
aggregate      copyToBuffer    flatten     indexWhere        lastOption           par            reduceRight         size            takeRight      toTraversable                  
andThen        corresponds     fold        indices           length               partition      reduceRightOption   slice           takeWhile      toVector                       
apply          count           foldLeft    init              lengthCompare        patch          repr                sliding         to             transpose                      
applyOrElse    diff            foldRight   inits             lift                 permutations   reverse             sortBy          toArray        union                          
asInstanceOf   distinct        forall      intersect         map                  prefixLength   reverseIterator     sortWith        toBuffer       unzip

Using these techniques you can start exploring the available APIs.

Scala – generate a list of random numbers

Using the scala fill operator, you can easily create a large list, and then populate that list with random entries:

val z = List.fill(1000)(10000).map(scala.util.Random.nextInt)

This will generate a list of 1,000 entries, each containing the number 10,000, which is used to generate a random number for that list entry (i.e. 0 to 10,000):

z: List[Int] = List(19436, 73559, 96382, 22910, 47398, 83820, 1630, 95466, 44891, 40060, 52702, 89086, 52120, 55565, 44399, 39384, 72965, 26512, 23219, 63453, 990, 37886, 2994, 86494, 41212, 46286, 65486, 44614, 35539, 72433, 9710, 20899, 62996, 12970, 75063, 61006, 3763, 44941, 89145, 32184, 56227, 61843, 93381, 3603, 75101, 81463, 47837, 61211, 86623, 38833, 83587, 287, 29393, 58860, 24595, 50864, 59747, 95237, 95245, 67748, 72658, 51490, 72874, 2855, 49481, 25293, 55248, 25664, 92292, 34892, 16992, 71963, 46768, 91903, 81261, 58776, 26798, 9205, 47431, 18671, 53079, 17322, 55733, 1277, 44473, 21537, 22465, 14512, 42176, 94234, 2286, 39820, 94704, 98961, 46788, 61623, 40974, 21683, 71372, 41895, 76286, 23357, 52151, 40870, 68518, 23155, 37816, 93887, 16082, 38841, 45650, 73544, 2289, ...

Scala fill example

“Fill” is a static collection method, as one of several ways to instantiate a static list.

If you want a list of several values, you could do something like this:

val x = List(0, 0, 0, 0, 0)

But, fill makes this easier:

scala> List.fill(0)(5)
res22: List[Int] = List(0, 0, 0, 0, 0)

You can pass anything into this:

scala> List.fill(5)("test")
res21: List[String] = List(test, test, test, test, test)

You can even make multi-dimensional arrays this way:

scala> List.fill(2, 3)(0)
res26: List[List[Int]] = List(List(0, 0, 0), List(0, 0, 0))
 
scala> List.fill(2, 3, 4)(0)
res27: List[List[List[Int]]] = 
  List(
    List(
      List(0, 0, 0, 0), 
      List(0, 0, 0, 0), 
      List(0, 0, 0, 0)), 
    List(List(0, 0, 0, 0),
         List(0, 0, 0, 0), 
         List(0, 0, 0, 0)))