Scala Introduction

by "Blag" - Senior Developer Evangelist

Return to Geeky Thursday

What is Scala?


Scala is a general-purpose programming language.

It provides support for functional and object oriented programming.

It has a strong static type system.

It runs on the JVM, and it's completely and totally interoperable with Java.

It also run on JavaScript -;).

It is really a breeze of fresh air...

How to install Scala


First things first...make sure that you have Java installed

On Linux flavored machines, simply install the package...


sudo apt-get install scala


For everything else...go to their website...

Scala download


Who uses Scala?


  • LinkedIn
  • Twitter
  • Netflix
  • Sony
  • AirBnB
  • Apple
  • IBM
  • Amazon
  • Autodeck

Starting out...


You can simply call it from the terminal

by typing "Scala"

Comments


Comments are very simple

				
//This is a commented line


/*This is a commented

   block*/
				

Variables


Variables can be either mutable or immutable


We can omit the variable class or we can include it...


				
val cannotchange = "Immutable"



var canChange: String = "Mutable"
				

Lists


Lists are pretty useful and probably the most used data structure in Scala

				
var myList = List(1,2,3)


myList = myList :+ 4


//myList becomes List(1,2,3,4)


for(c <- myList) {println(c)}

1

2

3

4
				

Sets


Sets are great for reduce functions

				
val unique = Set(10, 20, 30, 20, 20, 10)

val sum = unique.reduce( (a: Int, b: Int) => a + b )

println(s"\n$sum")

//60
				

Maps


Maps are hashes or key-value arrays

				
val myMap = Map("ABAP" -> "Procedural", 

                "Haskell" -> "Functional")

println(myMap("Haskell")

//Functional


for(pairs <- myMap) {println(pairs)}


//(ABAP, Procedural)

//(Haskell, Functional)
				

Functions


Function are very important...that's true for every programming language...

There's no need of a "return" if the last statement returns something...

				
def myFunc(a: Int, b: Int): Int = {

    a + b

}


println(myFunc(1,2))

//3
				

Anonymous Functions


We can also create Anonymous or Literal functions...

				
val increase: Int => Int = { case x: Int => x + 5 }


println(increase(12))


//17
				

Classes


Scala is also, Object Oriented -;)

				
class User(val name: String){

    def greet: String = s"Hello from $name"

    override def toString = s"User($name)"

}


val u = new User("Blag")

println(u.greet)

//Hello from Blag
				

Fibonacci list sequence


Finally...we're going to make our first application...


Name your file "Fibonacci.scala"


				
import scala.util.{Try, Success, Failure}


def fib(num: Int, a: Int, b: Int): String = {

    a > 0 && num > 1 match {

        case true => (a + b).toString + " " + 
        
                      fib((num - 1), (a + b), a)

        case false => a == 0 match {

            case true => a.toString + " " + 
            
                         b.toString + " " + 
                         
                         (a + b).toString + " " + 
                         
                         fib((num - 1), (a + b), b)

            case false => ""

        }

    }

}
				
				
val num = scala.io.StdIn.readLine("Please enter a

                                   Number: ")

if(Try(num.toDouble).isSuccess){

    print(fib(num.toInt,0,1))

}else{

    println("Please enter a number!")

}
				

When we run it we're going to see...


Making an LCD Number App


This is my favorite application of all time...


Name your file "LED_Numbers.scala"


				
import scala.util.{Try, Success, Failure}


val leds = Map("0" -> List(" _  ","| | ","|_| "),

               "1" -> List("  ","| ","| "),

               "2" -> List(" _  "," _| ","|_  "),

               "3" -> List("_  ","_| ","_| "),

               "4" -> List("    ","|_| ","  | "),

               "5" -> List(" _  ","|_  "," _| "),

               "6" -> List(" _  ","|_  ","|_| "),

               "7" -> List("_   "," |  "," |  "),

               "8" -> List(" _  ","|_| ","|_| "),

               "9" -> List(" _  ","|_| "," _| "))
				
				
val num = scala.io.StdIn.readLine("Please enter a 

                                   Number: ")

if(Try(num.toDouble).isSuccess){

    for( x <- 0 to 2 ) {

        for( y <- 0 to num.length - 1 ) {

            print(leds(num(y).toString)(x))

        }

        println("")

    }

}else{

    println("Please enter a number!")

}
				

When we run it we're going to see...


Random Names


This App will generate 100,000 random names using two 16 elements arrays


We will measure the runtime


Name your file "Random_Names.scala"


				
import scala.collection.mutable.ListBuffer

var list = time{
    
    val names = List("Anne","Gigi","Blag","Juergen",
    
                     "Marek","Ingo","Lars","Julia", 
    
                     "Danielle","Rocky","Julien",
                     
                     "Uwe","Myles","Mike","Steven",
                     
                     "Fanny")
                 
    
    val last_names = List("Hardy","Read","Tejada",
    
                          "Schmerder","Kowalkiewicz",
                          
                          "Sauerzapf","Karg","Satsuta",
                          
                          "Keene","Ongkowidjojo",
                          
                          "Vayssiere","Kylau","Fenlon",
                          
                          "Flynn","Taylor","Tan")
				
				
    var full_names = new ListBuffer[String]()

    val r = scala.util.Random

    for(i <- 0 to 100000){

        full_names += (names(r.nextInt(16)) + " " + 
        
                       last_names(r.nextInt(16)))

    }

}



print(list)

				
def time[R](block: => R): R = {  

    val t0 = System.nanoTime()

    val result = block

    val t1 = System.nanoTime()

    println("Elapsed time: " + (t1 - t0) + "ns")

    result

}
				

When we run it we're going to see...


Time is measured in nanoseconds...so that's about 0.16 seconds...

That's pretty fast...

Comparing it with Julia and Python...

Scala was faster that Python this time...although just for a tiny bit...

Decimal to Romans


This App will create a Roman Numeral based on a decimal number


This will include some nice commands...


Name your file "Decimal_to_Roman.scala"


				
import scala.collection.immutable.ListMap

import scala.util.Try


val roman_table = Map(1000 -> "M",900 -> "CM", 

                      500 -> "D",400 -> "CD",
                      
                      100 -> "C",90 -> "XC",

                      50 -> "L",40 -> "XL",
                      
                      10 -> "X",9 -> "IX",
                      
                      5 -> "V",4 -> "IV",
                      
                      1 -> "I")

                      
var orderRoman_Table = ListMap(roman_table.

                               toSeq.sortWith
                               
                               (_._1 > _._1):_*)
				
				
var keys = orderRoman_Table.keySet.toList

def show_romans(num: Int, ctr: Int): String = {

    val roman = keys(ctr)

    num > roman match{

        case true => roman_table(roman) + 
        
                     show_romans((num - roman), ctr)

        case false => num < roman && num > 0 match{

            case true => show_romans(num, (ctr + 1))

            case false => "" + roman_table(roman)

        }

    }

}
				
				
try{

    print("Enter a number: ")

    val num = scala.io.StdIn.readInt()

    println(show_romans(num, 0))

}catch{

    case e: NumberFormatException => 
    
            println("Please enter a number!")

}
				

When we run it we're going to see...


Counting Letters


In this example we're going to read a file and count how many time a letter appears...


Call your file "countletters.scala" (all in lowercase).


Create a file called "readme.txt" with the following text...


"This is a text file that we're going to read using scala"


				
import scala.io.Source

var lines = ""

for(line <- Source.fromFile("readme.txt").getLines())

lines = line

var letters = Map("" -> 0)

var counter = 0

for(line <- 0 to (lines.length - 1)){

    if(letters.contains(lines(line).toString)){

        counter = letters(lines(line).toString) + 1

        letters -= lines(line).toString

        letters += (lines(line).toString -> counter)

    }else{

        letters += (lines(line).toString -> 1)

    }

				
				
}


letters -= ""


for(pairs <- letters) {println(pairs)}
				

When we run it we're going to see...


That's it for now...


I hope you had some fun...


Scala is pretty awesome and you can code very quickly with it -;)


Contact Information


Blag --> blag@blagarts.com

@Blag on Twitter

Go back home...