getting started with scala

35
Getting Started with Scala Vikas Hazrati - [email protected] Meetu Maltiar - [email protected] OSScamp Delhi 2009

Upload: meetu-maltiar

Post on 06-May-2015

2.760 views

Category:

Technology


3 download

DESCRIPTION

This presentation was presented at OSS camp in New Delhi. It deals with the basics of Scala language and how we can use it to build scalable Applications

TRANSCRIPT

Page 1: Getting Started With Scala

Getting Started with Scala

Vikas Hazrati - [email protected]

Meetu Maltiar - [email protected]

OSScamp Delhi 2009

Page 2: Getting Started With Scala

Agenda

I. What is FP and OOP?

I. Introducing Scala – Scalable Languages – Scala is a Scripting

language – Scala is Java of future– Scala is OO– Scala is Interoperable

I. Features – Quick comparison

with Java– Function Values and

Closures– Traits– Pattern Matching

I. End Notes- Who is using it ?- Tool support- Learning resources

Page 3: Getting Started With Scala

I. What is FP and OOP?

Page 4: Getting Started With Scala

What is FP

Is a concept where you can pass functions as arguments, to store them in variables, and to return them from other functions.

Page 5: Getting Started With Scala

What is OOP?

Object Oriented Programming is programming which is oriented around objects

Takes advantage of Encapsulation, Polymorphism, and Inheritance to increase code reuse and decrease code maintenance.

Page 6: Getting Started With Scala

Scala: FP and OOP language

Scala is a object oriented and functional programming language which is completely interoperable with java

FP: Makes it easy to build interesting things from simple parts, using

– Higher order functions

– Algebraic types and pattern matching

– Parametric polymorphism

OOP: Makes it easy to adopt and extend complex systems using

– Subtyping and inheritance

– Dynamic configurations

– Classes as partial abstractions

Page 7: Getting Started With Scala

II. Introducing Scala

Page 8: Getting Started With Scala

8

Scalable languages

A language is scalable if it is suitable for very small as well as very large programs.

A single language for extension scripts and the heavy lifting.

Application-specific needs are handled through libraries and embedded DSL's instead of external languages.

Scala shows that this is possible.

Page 9: Getting Started With Scala

9

Scala is a scripting language

It has an interactive read-eval-print-loop (REPL).Types can be inferred.Boilerplate is scrapped.

scala> var capital = Map("US" → "Washington", "France" → "Paris")

capital: Map[String, String] = Map(US → Washington, France → Paris)

scala> capital += ("Japan" → "Tokyo")

scala> capital("France")

res7: String = Paris

Page 10: Getting Started With Scala

10

Scala is the Java of the futureIt has basically everything Java has now.

(sometimes in different form)It has closures.

(proposed for Java 7, but rejected)It has traits and pattern matching.

(do not be surprised to see them in Java 8, 9 or 10)It compiles to .class files, is completely interoperable and runs about as fast as

Java

object App { def main(args: Array[String]) { if (args exists (_.toLowerCase == "-help")) printUsage() else process(args) }}

Page 11: Getting Started With Scala

11

Scala is object-oriented

Every value is an objectEvery operation is a method callExceptions to these rules in Java (such as

primitive types, statics) are eliminated.scala> (1).hashCoderes8: Int = 1

scala> (1).+(2)res10: Int = 3

Page 12: Getting Started With Scala

12

Interoperability

Scala fits seamlessly into a Java environmentCan call Java methods, select Java fields, inherit Java

classes, implement Java interfaces, etc.None of this requires glue code or interface descriptionsJava code can also easily call into Scala codeScala code resembling Java is translated into virtually

the same bytecodes. ⇒ Performance is usually on a par with Java

Page 13: Getting Started With Scala

13

III. Scala Features

Page 14: Getting Started With Scala

14

Scala compared to Java

Scala adds Scala removes

+ a pure object system - static members

+ operator overloading - primitive types

+ closures - break, continue

+ mixin composition with traits

- special treatment of interfaces

+ existential types - wildcards

+ abstract types - raw types

+ pattern matching - enums

Page 15: Getting Started With Scala

15

Scala cheat sheet (1): Definitions

Scala method definitions:

def fun(x: Int): Int = { result}

def fun = result

Scala variable definitions:

var x: Int = expression

val x: String = expression

Java method definition:

int fun(int x) { return result}

(no parameterless methods)

Java variable definitions:

int x = expression

final String x = expression

Page 16: Getting Started With Scala

16

Scala cheat sheet (2): Objects and Classes

Scala Class and Object

class Sample(x: Int, val p: Int) { def instMeth(y: Int) = x + y}

object Sample { def staticMeth(x: Int, y: Int) = x * y}

Java Class with statics

class Sample { private final int x; public final int p; Sample(int x, int p) {

this.x = x; this.p = p;

} int instMeth(int y) { return x + y; } static int staticMeth(int x, int y) { return x * y; }}

Page 17: Getting Started With Scala

17

Scala cheat sheet (3): Traits

Scala Trait

trait T {

def abstractMth(x: String): Int

def concreteMth(x: String) =

x + field

var field = “!”

}

Scala mixin composition:

class C extends Super with T

Java Interface

interface T { int abstractMth(String x)}

(no concrete methods)

(no fields)

Java extension + implementation:

class C extends Super implements T

Page 18: Getting Started With Scala

18

Scala Compared to Java

class CreditCard(val number: Int, var creditLimit: Int)

javap -private CreditCard

public class CreditCard extends java.lang.Object implements scala.ScalaObject{ private int creditLimit; private final int number; public CreditCard(int, int); public void creditLimit_$eq(int); public int creditLimit(); public int number(); public int $tag() throws java.rmi.RemoteException;}

Page 19: Getting Started With Scala

19

Constructors

class Person(val firstName: String, val lastName: String) { private var position: String = _ println("Creating " + toString()) def this (firstName: String, lastName: String, positionHeld: String) { this (firstName, lastName) position = positionHeld } override def toString() : String = { firstName + " " + lastName + " holds " + position + " position " }}

Page 20: Getting Started With Scala

20

Statics in Scala

Page 21: Getting Started With Scala

21

Higher Order Functions

Page 22: Getting Started With Scala

22

Currying & Partial FunctionsCurrying in Scala transforms a function that takes more than oneparameter into a function that takes multiple parameter lists.

Page 23: Getting Started With Scala

23

Closures

You can create code blocks with variables that are not bound.

You will have to bind them before you can invoke the function; however,they could bind to, or close over, variables outside of their local scopeand parameter list.

That’s why they’re called closures.

Page 24: Getting Started With Scala

24

Closures

Page 25: Getting Started With Scala

25

TraitsThey are fundamental unit for code reuse in Scala

A Trait encapsulates method and field definitions, which can be reused by mixing them in classes

Unlike class inheritance , in which class must inherit from just one superclass, a class may mix in any number of Traits

Unlike Interfaces they can have concrete methods

Page 26: Getting Started With Scala

26

Traitstrait Philosophical {

def philosophize() {

println("I consume memory, therefore I am!")

}

}

class Frog extends Philosophical {

override def toString() = "green"

}

val latestFrog = new Frog

println("" + latestFrog)

latestFrog.philosophize()

val phil:Philosophical = latestFrog

phil.philosophize()

Page 27: Getting Started With Scala

27

Pattern Matching

All that is required is to add a single case keyword to each class that is to be pattern matchable

Similar to switch expect that Scala compares Objects as expressions

Page 28: Getting Started With Scala

28

Pattern Matchingobject PatternApplication {

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

println( simplifyTop(UnOperator("-", UnOperator("-", Variable("x")))))

println( simplifyTop(BinOperator("+", Variable("x"), NumberOperator(0))))

println( simplifyTop(BinOperator("*", Variable("x"), NumberOperator(1))))

}

def simplifyTop(expr: Expression): Expression = expr match {

case UnOperator("-", UnOperator("-", e)) => e // Double negation

case BinOperator("+", e, NumberOperator(0)) => e // Adding zero

case BinOperator("*", e, NumberOperator(1)) => e // Multiplying by one

case _ => expr

}

}

Page 29: Getting Started With Scala

29

IV. End Notes

Page 30: Getting Started With Scala

30

Tool support

– Standalone compiler: scalac

– Fast background compiler: fsc

– Interactive interpreter shell and script runner: scala

–Web framework: lift

– Testing frameworks: Specs, ScalaCheck, ScalaTest, SUnit, …

IDE plugins for:– Eclipse (supported by EDF)

– IntelliJ (supported by JetBrains)

– Netbeans (supported by Sun)

Page 31: Getting Started With Scala

31

Who’s using it?Open source projects:

liftwicketNetLogo SPDE: Scala branch for ProcessingIsabelle: GUI and code extractor

Companies:Twitter: infrastructureSony Pictures: middlewareNature.com: infrastructureSAP community: ESME company messagingReaktor: many different projectsMimesis Republic: multiplayer gamesEDF: trading, …

Page 32: Getting Started With Scala

32

Learning ScalaTo get started:

First steps in Scala, by Bill Venners published in Scalazine at www.artima.com

Scala for Java Refugees by Daniel Spiewack (great blog series)

To continue:

Programming in Scala, by Odersky, Spoon, Venners, published by Artima,com

Other books are in the pipeline.

Page 33: Getting Started With Scala

33

Page 34: Getting Started With Scala

34

Contact Us

Vikas Hazrati - [email protected]

Meetu Maltiar - [email protected]

www.xebiaindia.com

www.xebia.com

http://blog.xebia.in

http://blog.xebia.com

Page 35: Getting Started With Scala

35

References“Programming in Scala” book by Martin Odersky, Lex Spoon and Bill Venners

Presentation by Martin Odersky at FOSDEM 2009http://www.slideshare.net/Odersky/fosdem-2009-1013261

Online book on Scala by oreillyhttp://programming-scala.labs.oreilly.com/

Magazine for Scala Programming Communityhttp://www.artima.com/scalazine