Scala

Appeared in:
2003
Influenced by:
Paradigm:
Typing discipline:
File extensions:
.scala, .class
Versions and implementations (Collapse all | Expand all):
Programming language

Scala (from “scalable language”) is a high-level programming language which combines object-oriented and functional programming styles.

Examples:

Hello, World!:

Example for versions Scala 2.7.7-final, Scala 2.8.0-final
object Main {
    def main(args: Array[String]) {
        println("Hello, World!")
    }
}

Factorial:

Example for versions Scala 2.7.7-final

This example uses recursive factorial definition.

object Factorial {
    def factorial(n: Int): Long = 
        if (n == 0) 1 
               else n * factorial(n - 1)
    def main(args: Array[String]) {
        for {i <- List.range(0, 17)} 
            yield { println(i + "! = " + factorial(i)) }
    }
}

Factorial:

Example for versions Scala 2.7.7-final

This example uses iterative factorial definition.

object Factorial {
    def main(args: Array[String]) {
        var f = BigInt(1)
        format("0! = %s\n", f)
        for {i <- 1 to 16} {
             f *= i;
             format("%s! = %s\n", i, f)
        }
    }
}

Fibonacci numbers:

Example for versions Scala 2.7.7-final

This example uses recursive definition of Fibonacci numbers.

object Fibonacci {
    def fibonacci(n: Int): Int = 
        if (n < 3) 1 
              else fibonacci(n - 1) + fibonacci(n - 2)
    def main(args: Array[String]) {
        for {i <- List.range(1, 17)} 
            yield { print(fibonacci(i) + ", ") }
        println("...")
    }
}

Fibonacci numbers:

Example for versions Scala 2.7.7-final, Simply Scala

This example shows the usage of lazy evaluations and infinite lists in Scala. Infinite list of Fibonacci numbers is defined using functions .zip and .tail in the same way as in Haskell example.

lazy val fib: Stream[Int] = Stream.cons(1, Stream.cons(1, fib.zip(fib.tail).map(p => p._1 + p._2)))
fib.take(16).print

Quadratic equation:

Example for versions Scala 2.7.7-final, Scala 2.8.0-final

This example expands the interactive one with variables input.

import java.io.{BufferedReader, InputStreamReader}
 
object Main {
    def main(args: Array[String]) {
        var stdin = new BufferedReader(new InputStreamReader(System.in));
        var A = augmentString(stdin.readLine()).toInt;
        var B = augmentString(stdin.readLine()).toInt;
        var C = augmentString(stdin.readLine()).toInt;
        solve(A,B,C);
    }
    def output(real: Double, imag: Double): String = 
        if (imag == 0) ""+real
                  else "("+real+","+imag+")"
 
    def solve(A: Int, B: Int, C: Int)
    {   if (A == 0) print("Not a quadratic equation.")
        else
        {   def D = B*B - 4*A*C;
            if (D == 0) print("x = "+output(-B/2.0/A, 0));
            else if (D > 0) 
                      print("x1 = "+output((-B+Math.sqrt(D))/2.0/A, 0)+"\nx2 = "+output((-B-Math.sqrt(D))/2.0/A, 0));
                 else print("x1 = "+output(-B/2/A, Math.sqrt(-D)/2.0/A)+"\nx2 = "+output(-B/2/A, -Math.sqrt(-D)/2.0/A));
        }
    }
}

CamelCase:

Example for versions Scala 2.8.0-final

This example uses regular expressions twice. First one, words, describes the words in the text; each match of it is replaced with itself, converted to lower case and capitalized. Second one, separators, describes the spaces between words; all matches of it are replaced with empty string, i.e., just removed from the string.

import java.io.{BufferedReader, InputStreamReader}
import scala.util.matching.Regex
 
object Main {
    def main(args: Array[String]) {
        var stdin = new BufferedReader(new InputStreamReader(System.in));
        var text = stdin.readLine();
        val words = """([a-zA-Z]+)""".r
        text = words.replaceAllIn(text, m => m.matched.toLowerCase.capitalize)
        val separators = """([^a-zA-Z]+)""".r
        text = separators.replaceAllIn(text, "");
        println(text);
    }
}

Hello, World!:

Example for versions Simply Scala

In Simply Scala you can evaluate expressions without framing them as objects.

println("Hello, World!")

Factorial:

Example for versions Simply Scala

This examples shows how to define ! as a method applied to Int.

def factorial(n: Int): BigInt = 
    if (n == 0) 1 
           else factorial(n - 1) * n
class Factorizer(n: Int) {
    def ! = factorial(n)
}
implicit def int2fact(n: Int) = new Factorizer(n);	

for {i <- List.range(0, 17)} 
    println(i + "! = " + (i!))

Quadratic equation:

Example for versions Simply Scala

This example shows that string processing and Math in Scala are implemented similarly to Java.

def output(real: Double, imag: Double): String = 
    if (imag == 0) ""+real
              else "("+real+","+imag+")"

def solve(A: Int, B: Int, C: Int)
{   if (A == 0) print("Not a quadratic equation.")
    else
    {   def D = B*B - 4*A*C
        if (D == 0) print("x = "+output(-B/2.0/A, 0))
        else if (D > 0) print("x1 = "+output((-B+Math.sqrt(D))/2.0/A, 0)+"\nx2 = "+output((-B-Math.sqrt(D))/2.0/A, 0))
             else print("x1 = "+output(-B/2/A, Math.sqrt(-D)/2.0/A)+"\nx2 = "+output(-B/2/A, -Math.sqrt(-D)/2.0/A))
    }
}