Scala Method Notations

Infix Notation/Operator Notation
Method with one parameter can be accessed with space (Natural Language)

class Person {
  def sayHello(name: String) = println(s"Hello $name")
}
val person = new Person
person sayHello "Niranjan"

In scala we can also use +/-/*/#/$ as method names which makes it much more comfortable to code with unlike other languages. This is exactly what is happening in mathematical operators as they are also methods

    println(1 + 3)
    // ALL OPERATORS ARE METHODS in SCALA
    println(1.+(3))

PREFIX NOTATION or Unary Operator
A Unary Operator is also a METHOD in SCALA
All UNARY Operators are methods with prefix “unary_”

val x = -1
// Its same as
val y = 1.unary_-

POSTFIX Notation
Method with no parameter can be accessed without paranthesis

class Person {
  def sayHello = println("Hello")
}
val person = new Person
person.sayHello
// OR
person sayHello

Classes, Instances, Objects, Companion Object, Scala Application

Class in scala is used to wrap instance level functionality.

class Foo //class

Instance

val foo = new Foo // instance

Note: In scala, we do not call instance of a class as an Object because Object has a special meaning.

Object Scala Object is a Singleton Instance by definition.
SCALA DOES NOT HAVE CLASS LEVEL FUNCTIONALITY (like “static” in java) – Equivalet in scala is Object
Everytime an object is defined, this object will be of its own type (“type person”) and it itself is the only instance.
Objects can be defined in a similar way to that of the classes with the only difference being the constructor parameters.

object Person {
  val N_HANDS = 2 // static in java
}
val person1 = Person // refers to the only instance on Object
val person2 = Person
println(person1 == person2) // returns true

Companion Object
We can define class with the same name as that of object to seperate instance level functionality (Class) from static/class level functionality (Object), and when class and object exists with same name in one file, they are called COMPANION OBJECTS or COMPANIONS

object Person {
  val N_HANDS = 2 // static in java
}
class Person(name: String, val age: Int) {
  // where as name and age are instance specific and hence they are referred in class members
}

Note:
In Java we access static member via class name and instance member via object reference
But in Scala, we access class level memebers via Object and instance level members via the instance of a Class, It turns out to be more Object Oriented than JAVA eventhough its created for functional programming

Scala Application
When a scala object inherts scala.App trait it becomes scala application. The App trait can be used to quickly turn objects into executable programs.

object Main extends App {
  Console.println("Hello World: " + (args mkString ", "))
}

Call By Value vs Call By Name

Call By Value is just like any other programming language where we use the static value of the argument directly

     def calledByValue(x: Long): Unit = {
         println("by value: " + x)
         println("by value: " + x)
     }
     calledByValue(System.nanoTime())

Call By Name
Here instead of the value, the expression is passed as is and it will be evaluated by the compiler everytime. Call by Name is lazily evaluated.

     def calledByName(x: => Long): Unit = {
         // the arrow above is going to tell the compiler to evaluate the parameter by NAME
         // x is evaluated for every use
         println("by name: " + x)
         println("by name: " + x)
     }
     calledByName(System.nanoTime())

Lazy Evaluation example

def infinite(): Int = 1 + infinite()
def printFirst(x: Int, y: => Int) = println(x)

// println(infinite(), 34) // errors with stackoverflow

println(34, infinite()) // runs fine as second parameter is lazily evaluated and is never executed

Scala Type Hierarchy and Expressions

Type Hierarchy

Expressions
In imperative languages like Java/Python we execute instructions. For example IF conditional statement is an Instruction. Whereas in Scala, we execute expressions.

IF conditional statements are expressions that can return some value.

val aConditionValue = if (aCondition) 5 else 3
Code Blocks are also expressions that can return something
val someOtherValue = {
        if (someValue) 233 else 422
        42
    }

Code Blocks are commonly used expression blocks which can contain one or more expressions and the return type is the return value from the last expression.

val aCodeBlock = {
   if(true) 54
   56
}

Throwing exception from a method returns Nothing “()”
Any methods (println) that have side effects returns Unit
so on..

In functional programming languages writing loops are not encouraged. Whenever there is a need to write a loop we should go for recursion. Optimized way to write recursion is to use TAIL RECURSION technique.
To ensure we are using tail recursion we can use “@tailrec” before the function definition

Mawazo

Mostly technology with occasional sprinkling of other random thoughts

amintabar

Amir Amintabar's personal page

101 Books

Reading my way through Time Magazine's 100 Greatest Novels since 1923 (plus Ulysses)

Seek, Plunnge and more...

My words, my world...

ARRM Foundation

Do not wait for leaders; do it alone, person to person - Mother Teresa

Executive Management

An unexamined life is not worth living – Socrates

javaproffesionals

A topnotch WordPress.com site

thehandwritinganalyst

Just another WordPress.com site

coding algorithms

"An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem." -- John Tukey

%d bloggers like this: