programming in scala - 1

28
Programming in Scala By: http://changingtechblog.blogspot.in/

Upload: mukesh-kumar

Post on 31-May-2015

1.127 views

Category:

Technology


1 download

DESCRIPTION

Introduces scala programming language for those who are exploring use of scala for the next project.

TRANSCRIPT

Page 1: Programming in scala - 1

Programming in ScalaBy: http://changingtechblog.blogspot.in/

Page 2: Programming in scala - 1

Why Scala

● Java did wonderful things with its motto of "write once and run everywhere" but thats half the story

● Abundance of boilerplate in java● Java provided lower level of abstraction but its very

difficult to write multithreaded applications in java which runs as expected

● Multi core processors has opened an entire new dimension in programming world

● Thread safety, Visibility of data(Concurrency)● Java as a language hasn't evolved much since its

inception but JVM has evolved up to the extent that its performance has surpassed with native written code

Page 3: Programming in scala - 1

What is Scala

● Scala is port of many years of academic research on JVM

● SCAlable LAnguage● Statically typed

○ A variable is bound to a particular type for its lifetime its type can't be changed and it can only reference type-compatible instances

○ In dynamic typing the type is bound to a value not the variable so a variable might refer to a value of type A then be reassigned to a value of unrelated type X

○ Ruby, Python, Groovy, Javascript and Smalltalk are dynamically typed

Page 4: Programming in scala - 1

What is Scala

● Scripting language● Functional language● Object Oriented language● Concise and flexible syntax● Sophisticated type system● Scalable (performance)

Page 5: Programming in scala - 1

JVM Languages

ScalaOther JVMLanguages

JAVA

iconst_1istore_1iconst_1istore_2iload_1iload_2iaddint2byteistore_3iload_3ireturn

JVM

Clojure, Groovy, JRuby, Jython, Rhino, Fantom, Kotlin ...see also

Page 6: Programming in scala - 1

Installation

● Unix○ Command line Download, Extract jar file and add its

"bin" directory in classpath○ Scala IDE Download

● Windows○ Command line Download, Extract jar file and add its

"bin" directory in path variable○ Scala IDE Download

● Other methods○ Download STS or Eclipse and add scala ide as a

plugin○ Download Intellij-Idea community version and install

scala as a plugin

Page 7: Programming in scala - 1

A taste of Scala● REPL (Read eval print loop)● $ scala● scala>● scala> :help● scala> :imports● scala> println("Hello World")● scala> printf("%d", 1)● scala> 1 + 2

res0: Int = 3● scala> 1 + "to string will be called"

res1: String = 1to string will be called● Scala worksheet in eclipse

Page 8: Programming in scala - 1

A taste of Scala Continued ...class Upper {

def upper(strings : String*) : Seq[String] = {strings.map((s : String) => s.toUpperCase())

}}val up = new Upperprintln(up.upper("I", "am", "using", "Scala", "as", "scripting", "language"))run as - scala upper-script.scala

object Upper {def main(args : Array[String]) = {

args.map((s : String) => s.toUpperCase()).foreach(printf("%s ", _))println("")

}}run as - scalac upper.scalascala -cp . Upper I am using scala from compiled file

Page 9: Programming in scala - 1

Type less do more● No Semicolons

○ Fewer characters to clutter your code○ Increases code readability by breaking statements in

separate line● Curly braces are not mandatory in all cases

○ class A○ def add(a : Int, b : Int) = a + b

● 'return' keyword is optional ● Method without parentheses and dots

○ "hello".length() vs "hello".length vs "hello" length○ 1. +(2) vs 1 + 2○ def isEven(n : Int) = n % 2 == 0○ List(1,2,3,4) filter isEven foreach println

● if statements are expressions in scala so there is no special ternary conditional expression

Page 10: Programming in scala - 1

Variable declaration● val

○ immutable (read only)○ scala> val array : Array[String] = new Array(5)

scala> array(0) = "Hello"scala> array

○ scala> val list : List[Int] = List(1,2,3)scala> 23 :: listscala> list

● var○ mutable ○ can assign a new value as often as you want

● Both val and var must be initialized when declared except in abstract types and constructor arguments

● Scala encourages you to use immutable variables whenever possible

Page 11: Programming in scala - 1

Literals● Integer literals

○ Byte, Char, Short, Int, Long○ 'l' or 'L' is required for Long

● Floating-Point literals○ Float, Double○ 'f' or 'F' is required for Float○ 'd' or 'D' is optional for Double

● Boolean (true, false)● Character literals

○ Printable unicode character or an escape sequence written between single quotes. Try '\u0041'

● String literals○ Sequence of characters enclosed in double quotes or

triples of double quotes. Try "Tab\tis escaped", """Tab\tis not escaped in triples of double quotes"""

Page 12: Programming in scala - 1

Literals Continued ...● Symbol literals

○ symbols are single quote followed by a letter followed by zero or more digits or letters

○ these are interned strings meaning two symbols with same name will actually refer to same objects.

○ Try 'id, '1○ Not used much in scala but popular in other

languages like Ruby, Smalltalk and Lisp● Tuples

○ To return multiple values in java either pass it in method parameters or return a object or a class which contains these values

○ scala has built in support for tuples of members from 1 to 22

○ scala> val pair = (1, "Hello")

Page 13: Programming in scala - 1

Literals Continued ...● Function literals

○ Function literal is an alternate syntax to define a function

○ val add = (a : Int, b : Int) => a + b○ val test = () => System.getProperty("user.dir")○ Useful for passing as argument in higher order

functions● Other literals

○ List■ val v1 = Nil■ val fruit = List("orange", "mango")

○ Map■ val stateCapital = Map("UP" -> "Lucknow",

"Bihar" -> "Patna") ■ val districtCount = Map(("UP", 84), ("Bihar", 40))

Page 14: Programming in scala - 1

Identifirs● Scala allows all printable ASCII characters

except parenthetical characters ( ) [ ] { } and delimeter characters ` ' " . , ;

● It also allows operator characters such as + - % / < > etc

● Reserved words can't be used● Underscore is important it tells the compiler to

treat all characters up to next whitespace as part of identifier

● After underscore you can have either letters and digits or a sequence of operator characters but you can't mix them with letters and digits

● An identifier can also be arbitrary string between two back quote characters

Page 15: Programming in scala - 1

Classesclass Person(firstName : String, lastName : String, age : Int) {}

● Primary Constructor - defined with class declaration● Auxiliary Constructor - defined as a method this(.....)● Constructor arguments can have access modifier such as

private, protected etc.● Arguments in primary constructor becomes instance

variables with setters and getters automatically generated depending upon variable scope, like val, var private, protected.

● Methods, instance variables can be overridden in subclass using override keyword Example: 'override def toString = "" '

Page 16: Programming in scala - 1

Classes continued ...Subclass must extend one of the constructor of superclassclass Person(name : String, val age : Int) {

def this() = this("No name", 25)def incrementAge(value : Int) = age += value

}// Extending primary constructorclass SmartPerson(name : String, override val age : Int) extends Person(name, age)*** override keyword is must with vals// Extending Auxiliary constructorclass UnknownPerson extends Person {

override def incrementAge(value : Int) = {if(value > 0) super.incrementAge(value) else throw new Error("Value can't be < 0)

Page 17: Programming in scala - 1

Method declaration

● Starts with a def keyword followed by optional argument list, a colon character and the return type of the method, an equal sign and finally the method body

● Method arguments can have default value● Method parameter order can be changed by

caller● Method definition can also be nested

Page 18: Programming in scala - 1

Abstract Class● Starts with abstract keyword, It can have both primary and auxiliary

constructors● If a method doesn't have a body then it automatically becomes

abstract same for instance variables● Abstract method must only be declared in abstract class or traits

but not in concrete class● Abstract class may not contain any abstract method or field but its

subclass must override all abstract members except if it another abstract class or traitabstract class Vehicle(val model : String) {

val engineNumber : Stringvar fuel : Doubledef addFuel(amount : Double) }

class Car(override val model : String) extends Vehicle(model) {val engineNumber = "dfdf"var fuel = 0def addFuel(amount : Double) ... }

Page 19: Programming in scala - 1

equals and hashcode

● java 'equals' equivalent in scala is 'eq'● See Scala Source Code● Scala provides 3 methods for checking equality of

objects/references● eq -> final method in AnyRef, checks equal reference● equals -> calls eq in AnyRef, must override it if you want to

check object equality instead of reference equality, structure def equals(that : Any) "that must be Any"

● == -> final method which calls equals with null checked● ne -> anti of eq● must override hashcode whenever overriding equals● Example in Person class

Page 20: Programming in scala - 1

Companion Object● A way to create singleton object, and separate class level

stuffs with object level stuff● starts with 'object' keyword in place of 'class' in class

declaration except that it has only default constructor● It must be defined in same file with same name as actual

class for which it is a companion object● apply, unapply methods

class Rational(x: Int, y: Int) { ... }object Rational {

def apply(x : Int, y : Int) = new Rational(x, y)def unapply(rational : Rational) = if(rational == null) None else

Some(rational.numer, rational.denom)

● Now we can define val rational = Rational(23, 45)

val Rational(x : Int, y : Int) = Rational(4, 5)

Page 21: Programming in scala - 1

Use of None instead of null● Scala discourages the use of null to avoid

NullPointerException or unnecessary null check● It provides two implementations of Option[+A] sealed

abstract class● None -> container has no value● Some -> container has some value● If a method can return null then it must be returned as Option

[A]● Always try to use getORElse rather than getExample:scala> var x : Option[String] = Nonescala> x.getscala> x.getOrElse("No Value")scala> x = Some("has some value")scala> x.getOrElse("No Value")scala> x = Option(null)scala> x = Option("Something")

Page 22: Programming in scala - 1

Discussions

● List, Vector, Stream● Last session exercises● Package objects● File IO

Page 23: Programming in scala - 1

Traits● Same as java interfaces with ability to have

implementation of methods and variable declaration

● It solves boilerplate code generated with using java interface

● It also gives ability to compose behaviour on demand

trait Culturetrait SouthIndianCulture extends Culturetrait BihariCulture extends Culturetrait ModernCulture extends Cultureclass Person extends Cultureval mukesh = new Person with BihariCulture with ModernCultureval modernPerson = new Person with ModernCultureval idiot = new Person

Page 24: Programming in scala - 1

Traits Contd ...● Traits can't have primary or auxiliary constructors● A class can mixin multiple traits using "with" keyword except first

trait starts with "extends"● It has a well defined algorithm for the order in which it is called

when a class is mixed in with multiple traits● It provides late binding "super call from a trait depends upon the

order in which it is mixing in"trait Atrait B extends Atrait C extends Bclass D extends A with B with C*Start with Class and then from right to left write its name expand if neededD - The classD C B A - Expande CD C B A B A - Expand BD C B A B A A - Expand ANow starting from right keep first one and remove any other repetition of that typeD C B A ScalaObject AnyRef Any - This will be final call order

Page 25: Programming in scala - 1

Traits Contd ...● Traits can extend a class, abstract class which has no

parameter primary or auxiliary constructor● self type - mechanism to refer to "this"trait T1trait T2 {

self =>}trait T3 {

self : T1 =>}// fineclass C extends T2// Compilation error, it must extend T1 because it was force in // definition of T3class C1 extends T3

Page 26: Programming in scala - 1

Types● Type is a set of information the compiler knows which is

used to infer whether a statement will succeed or fail● In Scala A type can be one of object, class, trait or

defined with type keyword● class and trait types are accessible directly but object

types are accessed with objectname.type● Structural type defines what method/variable signature

you might expect on a particular type. It should be avoided as it uses reflection

Exampleobject Otype abstractTypetype concreteType = Stringtype concreteType = C with Ttype objectType = O.type

Page 27: Programming in scala - 1

Structural Types// A type closeable must have close methodtype Closeable = {def close : Unit}

// Define a method with parameter closeabledef testClose(closeable : Closeable) = closeable.close

// We can call this method on any class or trait which has// close method in its scope, above method is applicable for all threeclass C { def close = println("closing in C") } trait T { def close = println("closing in T") } class C1 extends T

Page 28: Programming in scala - 1

Thank You

http://changingtechblog.blogspot.in/