Sunday, February 19, 2012

Scala - My Three Hours Exploration

Before we start, you can run the Scala Interpreter on Eclipse with Scala Plugin by going to Window -> Show -> Scala Interpreter then you can execute snippets of code on it.

Everything in Scala is expression. Moreover, Scala interpretation will automatically assign the proper data type for the result of an expression like the provided example below:
1 + 1
result: Int = 2

In the given, Scala determined the result of adding one to itself will be an integer.

Difference between Values and Variables:

Values (val) are expression that is once linked to an expression that will never be reassigned to another expression. It's like a variable defined with final in java
Variables (var) that are expressions that can be rebind.

val two = 1 + 1
two: Int = 2

two = 2 + 2
error: reassignment to val

var three = 2 + 1
three: Int = 3

three = 3 + 3
three: Int = 6

Function in Scala
In scala, you can create function with def:
def functionName(identify: dataType, ...) : returnType = (expression)

def addOne(m: Int): Int = m + 1
addOne: (m: Int)Int

You can use know addOne by:
val four = addOne(3)
four: Int = 3

You can also leave off parameters of function doesn’t have params. On the other hand, if the return type can also not be specified, you can try the following:
def ten() = 5 + 5
three: ()Int

Int = 10

Int = 10

You can also create anonymous functions.
(identify: datatype, ..) => (expression)

(x: Int, y: Int) => x + y
(Int) => Int =

You can pass anonymous functions around or save them into vals or vars.

val add = (x: Int, y: Int) => x + y

var result= add(5,23)
result: Int = 28

If your expression is more than one line enclose it with {}. This is also true for anonymous function shown below:

def displayResult(x: Int, y: Int): Unit = {println("sum = " + (x + y))}

Scala has this new Partial Application (which is something new for me). Here you can partially apply a function with an underscore, which gives you another function:
val add2 = adder(2, _:Int)
add2:(Int) => Int =

Int = 5

Curried function (something new to me also)

This is a technique of transforming a function that takes multiple arguments (or an n-tuple of arguments) in such a way that it can be called as a chain of function, each with a single argument which technique is present in scala by:

def multiply(m: Int)(n:Int): Int = m * n

val timesTwo = multiply(2)(_)


In the example, multiply take in one parameters which is m and returns a function as a result, then calls this function, passing the second parameters. This function computes the value and return the final result. Let's think of it as a method with an anonymous inner class.

Making Function a Curried (in here I Curried add function)

Syntax for methods that can take parameters of a repeated type:
def capitalizeAll(args: String*) = { { arg =>

this is like the ellipse (..) in java


class Calculator {
 var brand: String = "HP"
 def add(n: Int, m: Int): Int = {
   n + m

val calc = new Calculator

Class with constructor

class Calculator(var brand: String) {
 var color: String = if (brand == "HELLO") {
 } else {
 } //everything is scala really is an expression

 def add(n: Int, m: Int): Int = {
   n + m

var calc = new Calculator("Cann")

In first line, you defined a calculator with brand as a variable member and also you defined a constructor for Calculator class accepting a String that will be the value of brand.

Inheritance on Scala

class ScientificCalculator(brand: String) extends Calculator(brand) {
 def log(m: Double, base: Double) = math.log(m) / math.log(base)

same in java, scala uses extends for inheritance.

Overloading methods

class EvenMoreScientificCalculator(brand: String) extends ScientificCalculator(brand) {
 def log(m: Int) = log(m, math.exp(1))

Similar to interfaces in Java, traits are used to define object types by specifying the signature of the supported methods or variables. Unlike Java, Scala allows traits to be partially implemented, i.e. it is possible to define default implementation for some method.

trait Car {
 val brand: String

class BMW extends Car {
 val brand = "BMW"

trait Similarity {
 def isSimilar(x: Any): Boolean
 def isNotSimilar(x: Any): Boolean = !isSimilar(x)

class Point(xc: Int, yc: Int) extends Similarity {
 var x: Int = xc
 var y: Int = yc
 def isSimilar(obj: Any) =
   obj.isInstanceOf[Point] &&
   obj.asInstanceOf[Point].x == x

Function can also be generic and work on any type. This is like generic typing in java. Types uses square bracket like:

trait Cache[K, V] {
 def get(key: K): V
 def put(key: K, value: V)
 def delete(key: K)

method with types

def remove[K](key: K)

Class with type

class Stack[T] {
 var elems: List[T] = Nil
 def push(x: T) { elems = x :: elems }
 def top: T = elems.head
 def pop() { elems = elems.tail }

Calling a class with type

val stack = new Stack[Int]

Apply method

In Scala, any object that has an apply method can be called with the .apply omitted.

class Array{
def apply(index:Int) = {println(index)}

2 ways to call apply:
val a = new Array()


Object in scale used to hold single instances of a class. (Singleton)

object Timer {
 var count = 0

 def currentCount(): Long = {
   count += 1

to call currentCount:

Difference between Class and Object

A class is a definition, a description. It defines a type in terms of methods and composition of other types while object is a singleton, object has no constructor (one instance on one application)

This is my first time to write about programming language and I get pleasure from it . Scala is a great and well- designed language. It’s better than java in almost all aspects (too early for my conclusion, I just employ it in 3 hours) and more fun than ruby (being playing with ruby with rails framework for almost 3 months now). I believe that the community is not that large compare to ruby or java but it’s a great language to explore. Hope to use it in real action someday.


No comments:

Post a Comment