SlideShare a Scribd company logo
1 of 34
INTRODUCTION TO SCALA
                       PART I
       BY:-   GIRISH KUMAR A L
What is SCALA ?
1. Martin Odersky

2. General purpose programming language.



1. It blends in “Object Oriented” and “functional Programming”
   paradigms.

2. SCALA’s innovations come primarily from how its constructs are
   put together.
What is SCALA ?
Functional Programming:
    Is a programming paradigm where we try to divide programs into
functions, which have no side effects i.e. don’t change program state
and void mutable data. Eliminating side effects can make it much
easier to understand and predict the behavior of a program.
What is SCALA ?
Object-oriented-programming:
  Is a programming paradigm where programs are divided into
containers called Objects which have data fields and
behavior(methods). SCALA is a pure OOP language.
SCALA and JAVA
        SCALA
                              JAVA
                                               C++
                                                             C


1. SCALA was written keeping in mind that “its impractical” to
come-up with a new programming language and make it widely
acceptable without interoperating with applications from Java.

2. “Java code can call SCALA code” and “SCALA code can can java
code”. Scala gets compiled into Java Byte codes, which gets executed
on Java virtual machine.
SCALA AND JAVA
1. So, SCALA was written for Java programmers ?.

2. Most of the courses, books and tutorials assume that you already
   know java or at least OOP.



   But
SCALA for a C language
                     PROGRAMMER.
 There is no shortcut here.


 First go and learn Java , or at least go here :
http://docs.oracle.com/javase/tutorial/java/index.html , and ramp up on
Basic OOP concepts.

 New and important features of SCALA such as pattern matching, Traits
  and compositions need OOP concepts.

 Even basic language constructs like If-else, for loops, function
  declarations and definitions, etc. are quite different , and not only with
  respect to syntax.
BUT why SCALA ?
1.    A lot of interesting companies like Twitter, Foursquare and
     LinkedIn are using/adopting SCALA.

1. There are even some VIM plugins around.

2.   Good build tool support like SBT, Maven, Ant etc..

3. SCALA is now in its v2.10. Lot of new features every release.

5. And it is not like IPv4 to IPv6 transformation. It must be fairly
   easy for java based applications to port to SCALA.
1.
     SOME attractive features OF scala
      Variables in SCALA.
      1.   Variable Immutability.
      2.   Type inference.


2.    Functions in SCALA.
      1.   Anonymous Functions.


3.    SCALA control constructs.
      1.   If expression.
      2.   For expression.


4.    Pattern Matching.
      1.   With Constants.
      2.   With Regular expressions.
Variables in SCALA: VAL AND VAR
When programming in C, If we want a variable, most of us will be
thinking in these steps



1.    I need an Integer


                   int
VAL AND VAR
1.Let me give it a name “x”, that declares x. This is enough we can go
ahead ,but…




                int x;
VAL AND VAR
1. Let me initialize it to 0, to be safe.   This defines x(allocates
memory)




                  int x = 0;
VAL AND VAR
In SCALA we will have to think in this way:

1. I need a mutable or a immutable field? i.e. val or var ? Lets go
   with a val.




                val
VAL AND VAR
2. Let me name it “x”.




               val x
VAL AND VAR
3. OK I need it to be an Integer




                  val x: Int
VAL AND VAR
3. Let me initialize it to 0. This ends the value definition.

                                         val x: Int = 0
4.    But scala has “Type inference” right!? Why do I need to type it as “Int”. Yes we can omit it. Its enough just to
      have this:



                                               val x = 0
TYPE inference in SCALA

val s = “STRING”

var x = (1, “ONE”)
Function DEFINITIONS
In C


int factorial(int x) {
 if(x == 1)
     return x;
 else
     return x * factorial(x - 1);
}
Function Definitions
• In SCALA


                      • def factorial(x: Int): Int = {
                         if(x == 1) x
               else    x * factorial(x - 1)
           }


• So this function is of type (Important!)


                              • (Int) => Int
Function Definitions
• If there is no parameter to function!


• def function1(): Int = {
   255
• }

• We can even forget about () and Int!!


• def function2 = {
• 1+2
• }         // These functions are of type () => Int
Function Definitions
• If the function is not returning anything then we can forget about
  “=”


    def function3 {
    //Body
    }

If the function body is of only one line then we can even forget about
“{ }”


    def function4 = 1
FUNCTION LITERALS
1. Also called as Anonymous Functions, these functions are not
   bound to an identifier. Can be written in below format in SCALA.

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

2. These functions can be passed as arguments to “Higher-order
   functions”.

   def higherOrderFunc(f: (Int, Int) => Int) : Int;
SCALA IF EXPRESSION
It looks similar to if in C, but SCALAS “if” is an expression. So it
returns a value.
                          if(!args.isEmpty) args(0)
                            else “default.txt”
And it can be used inside function calls, and as function bodies.
   println(if(!args.isEmpty) args(0) else “default.txt”)
           OR
   def function(args: Array[String]): String =
       if(!args.isEmpty) args(0) else “default.txt”
SCALA FOR EXPRESSION
For expression in SCALA is the Swiss army knife of iteration.

    for ( generator definition filter)

1. Iteration through an Array.
                         for (x <- 0 to 100)
                OR

              for (x <- 0 until 100)
                 OR just

              for(x <- args)
SCALA FOR EXPRESSION
2. Using Filters

    for ( x <- 1 to 100 if x%2 == 0) println(x)

You can use multiple filters :

    for {     x <-1 to 100
         if x%2 == 0
         if x%3 == 0 } println(x)

    for (x <- args if x.matches(“^d*$”)) println(x)
SCALA FOR EXPRESSION
3. Using definitions

    for (x <- args y = x.length if y <= max) println(x)

4 . Multiple Generators:

    for (x <- args y <- x) println(y)

5. Returning from a for expression using Yield

  val y = for(x <- 1 to 100 if x%3 == 0) yield x
Pattern Matchinga construct called
Pattern matching in scala is done with the help of
match which looks similar to c language switch.

Simple example: pattern matching with constants

x match {
   case “-help” | “-h” => displayHelp
   case “-version” | “-v” => displayVersion
   case _       => process
}
Pattern Matching with Regular
                        expressions
A simple example, with regular expressions

val regex = "(^d*$)".r

def patternMatch(x: String) = x match {
    case regex(a) => println("matched")
    case _      => println("Did Not matched")
}

patternMatch("1234")
patternMatch("abcd")
KEY DIFFRENCES BETWEEN C AND SCALA
Comparable features                C                                                    SCALA
Programming paradigm               Imperative programming                               Functional and object oriented programming


Compiler                           Compiled to machine code                             Compiled to Byte codes


High-level Data-structures         No Language support, but libraries are added on      Lists[T], Maps[T,M], Set[T], SortedSet[T,M]
                                   top using primary data types
Concurrency                        With Help of locks and shared-memory                 With help of actors, share nothing strategy. But
                                                                                        still supports locks and shared-memory.

Scripting                          No scripting support                                 Scripting support


Memory management                  Logic has to be built into the application code to   Garbage collector frees memory as soon as it
                                   free allocated memory.                               goes out of scope
Pattern Matching                   No support                                           Pattern matching with help of case classes,
                                                                                        regular expressions.


Performance Benchmarking           Highly optimized C ++ , short run time code is       -----------
                                   about 3 times faster.
Debuggability / Maintenance        Difficult to debug as everything is mutable          Much easier to debug as mostly everything can
                                                                                        be immutable.
Development                        Longer development time.                             Most concise language constructs reduce
                                                                                        development time and number of lines of code
                                                                                        by half compared to Java.

                 Source: Google benchmarks C++, Go, Java and SCALA Performance
1.
          Other Features of SCALA
     Singleton Objects.
2.   Pattern Matching with case classes.
3.   Stackable features with Traits.
4.   Companion objects and Factory Methods.
5.   Synchronized collections.
6.   Concurrent programming with Actors.

These and more can be covered in Part II.
1.
                        References
   Official Scala API database:
http://www.scala-lang.org/api/current/index.html#package

2. Programming in SCALA second edition by Martin Odersky

3. Scala Tutorial at
http://www.tutorialspoint.com/scala/index.htm
Q&A
THANK YOU

More Related Content

What's hot

Real-World Scala Design Patterns
Real-World Scala Design PatternsReal-World Scala Design Patterns
Real-World Scala Design PatternsNLJUG
 
The Evolution of Scala
The Evolution of ScalaThe Evolution of Scala
The Evolution of ScalaMartin Odersky
 
Scala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationScala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationMartin Odersky
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalMichael Stal
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersMiles Sabin
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stalMichael Stal
 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpMichael Stal
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaMichael Stal
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
IntroductiontoprogramminginscalaAmuhinda Hungai
 
Scala Language Intro - Inspired by the Love Game
Scala Language Intro - Inspired by the Love GameScala Language Intro - Inspired by the Love Game
Scala Language Intro - Inspired by the Love GameAntony Stubbs
 
About Functional Programming
About Functional ProgrammingAbout Functional Programming
About Functional ProgrammingAapo Kyrölä
 
Core java concepts
Core java  conceptsCore java  concepts
Core java conceptsRam132
 
Programming in Scala - Lecture One
Programming in Scala - Lecture OneProgramming in Scala - Lecture One
Programming in Scala - Lecture OneAngelo Corsaro
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture TwoAngelo Corsaro
 

What's hot (19)

Scala test
Scala testScala test
Scala test
 
Real-World Scala Design Patterns
Real-World Scala Design PatternsReal-World Scala Design Patterns
Real-World Scala Design Patterns
 
The Evolution of Scala
The Evolution of ScalaThe Evolution of Scala
The Evolution of Scala
 
Scala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationScala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentation
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Introducing Akka
Introducing AkkaIntroducing Akka
Introducing Akka
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 
Scalax
ScalaxScalax
Scalax
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stal
 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharp
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
Introductiontoprogramminginscala
 
Scala Language Intro - Inspired by the Love Game
Scala Language Intro - Inspired by the Love GameScala Language Intro - Inspired by the Love Game
Scala Language Intro - Inspired by the Love Game
 
About Functional Programming
About Functional ProgrammingAbout Functional Programming
About Functional Programming
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Scala basic
Scala basicScala basic
Scala basic
 
Programming in Scala - Lecture One
Programming in Scala - Lecture OneProgramming in Scala - Lecture One
Programming in Scala - Lecture One
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
 
Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
 

Viewers also liked

Jump Start into Apache Spark (Seattle Spark Meetup)
Jump Start into Apache Spark (Seattle Spark Meetup)Jump Start into Apache Spark (Seattle Spark Meetup)
Jump Start into Apache Spark (Seattle Spark Meetup)Denny Lee
 
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...Databricks
 
Scala - A Scalable Language
Scala - A Scalable LanguageScala - A Scalable Language
Scala - A Scalable LanguageMario Gleichmann
 
Scala: Pattern matching, Concepts and Implementations
Scala: Pattern matching, Concepts and ImplementationsScala: Pattern matching, Concepts and Implementations
Scala: Pattern matching, Concepts and ImplementationsMICHRAFY MUSTAFA
 
Scala eXchange: Building robust data pipelines in Scala
Scala eXchange: Building robust data pipelines in ScalaScala eXchange: Building robust data pipelines in Scala
Scala eXchange: Building robust data pipelines in ScalaAlexander Dean
 
Hive User Meeting August 2009 Facebook
Hive User Meeting August 2009 FacebookHive User Meeting August 2009 Facebook
Hive User Meeting August 2009 Facebookragho
 
DataEngConf SF16 - Spark SQL Workshop
DataEngConf SF16 - Spark SQL WorkshopDataEngConf SF16 - Spark SQL Workshop
DataEngConf SF16 - Spark SQL WorkshopHakka Labs
 
Spark Meetup TensorFrames
Spark Meetup TensorFramesSpark Meetup TensorFrames
Spark Meetup TensorFramesJen Aman
 
Hive Training -- Motivations and Real World Use Cases
Hive Training -- Motivations and Real World Use CasesHive Training -- Motivations and Real World Use Cases
Hive Training -- Motivations and Real World Use Casesnzhang
 
A Basic Hive Inspection
A Basic Hive InspectionA Basic Hive Inspection
A Basic Hive InspectionLinda Tillman
 
Functional Programming and Big Data
Functional Programming and Big DataFunctional Programming and Big Data
Functional Programming and Big DataDataWorks Summit
 
Spark Sql for Training
Spark Sql for TrainingSpark Sql for Training
Spark Sql for TrainingBryan Yang
 
Beyond SQL: Speeding up Spark with DataFrames
Beyond SQL: Speeding up Spark with DataFramesBeyond SQL: Speeding up Spark with DataFrames
Beyond SQL: Speeding up Spark with DataFramesDatabricks
 

Viewers also liked (20)

Zaharia spark-scala-days-2012
Zaharia spark-scala-days-2012Zaharia spark-scala-days-2012
Zaharia spark-scala-days-2012
 
Jump Start into Apache Spark (Seattle Spark Meetup)
Jump Start into Apache Spark (Seattle Spark Meetup)Jump Start into Apache Spark (Seattle Spark Meetup)
Jump Start into Apache Spark (Seattle Spark Meetup)
 
Apache hive
Apache hiveApache hive
Apache hive
 
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
 
Python to scala
Python to scalaPython to scala
Python to scala
 
Scala - A Scalable Language
Scala - A Scalable LanguageScala - A Scalable Language
Scala - A Scalable Language
 
Indexed Hive
Indexed HiveIndexed Hive
Indexed Hive
 
Fun[ctional] spark with scala
Fun[ctional] spark with scalaFun[ctional] spark with scala
Fun[ctional] spark with scala
 
Scala: Pattern matching, Concepts and Implementations
Scala: Pattern matching, Concepts and ImplementationsScala: Pattern matching, Concepts and Implementations
Scala: Pattern matching, Concepts and Implementations
 
Scala eXchange: Building robust data pipelines in Scala
Scala eXchange: Building robust data pipelines in ScalaScala eXchange: Building robust data pipelines in Scala
Scala eXchange: Building robust data pipelines in Scala
 
Hive User Meeting August 2009 Facebook
Hive User Meeting August 2009 FacebookHive User Meeting August 2009 Facebook
Hive User Meeting August 2009 Facebook
 
DataEngConf SF16 - Spark SQL Workshop
DataEngConf SF16 - Spark SQL WorkshopDataEngConf SF16 - Spark SQL Workshop
DataEngConf SF16 - Spark SQL Workshop
 
Spark Meetup TensorFrames
Spark Meetup TensorFramesSpark Meetup TensorFrames
Spark Meetup TensorFrames
 
Hive Training -- Motivations and Real World Use Cases
Hive Training -- Motivations and Real World Use CasesHive Training -- Motivations and Real World Use Cases
Hive Training -- Motivations and Real World Use Cases
 
A Basic Hive Inspection
A Basic Hive InspectionA Basic Hive Inspection
A Basic Hive Inspection
 
Functional Programming and Big Data
Functional Programming and Big DataFunctional Programming and Big Data
Functional Programming and Big Data
 
Spark Sql for Training
Spark Sql for TrainingSpark Sql for Training
Spark Sql for Training
 
Beyond SQL: Speeding up Spark with DataFrames
Beyond SQL: Speeding up Spark with DataFramesBeyond SQL: Speeding up Spark with DataFrames
Beyond SQL: Speeding up Spark with DataFrames
 
Hive tuning
Hive tuningHive tuning
Hive tuning
 
Functional Programming in Scala
Functional Programming in ScalaFunctional Programming in Scala
Functional Programming in Scala
 

Similar to Introduction to scala for a c programmer

Scala final ppt vinay
Scala final ppt vinayScala final ppt vinay
Scala final ppt vinayViplav Jain
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Courseparveen837153
 
Functional Programming In Jdk8
Functional Programming In Jdk8 Functional Programming In Jdk8
Functional Programming In Jdk8 Bansilal Haudakari
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With ScalaMeetu Maltiar
 
Basics java programing
Basics java programingBasics java programing
Basics java programingDarshan Gohel
 
Java programing language unit 1 introduction
Java programing language unit 1 introductionJava programing language unit 1 introduction
Java programing language unit 1 introductionchnrketan
 
Scala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologistScala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologistpmanvi
 
An Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional ParadigmsAn Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional ParadigmsMiles Sabin
 
Spark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin OderskySpark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin OderskySpark Summit
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageAzilen Technologies Pvt. Ltd.
 
Martin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaMartin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaScala Italy
 
Scala overview
Scala overviewScala overview
Scala overviewSteve Min
 

Similar to Introduction to scala for a c programmer (20)

Scala final ppt vinay
Scala final ppt vinayScala final ppt vinay
Scala final ppt vinay
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Course
 
Functional Programming In Jdk8
Functional Programming In Jdk8 Functional Programming In Jdk8
Functional Programming In Jdk8
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Basics java programing
Basics java programingBasics java programing
Basics java programing
 
Start with swift
Start with swiftStart with swift
Start with swift
 
Quick introduction to scala
Quick introduction to scalaQuick introduction to scala
Quick introduction to scala
 
Devoxx
DevoxxDevoxx
Devoxx
 
Java programing language unit 1 introduction
Java programing language unit 1 introductionJava programing language unit 1 introduction
Java programing language unit 1 introduction
 
Scala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologistScala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologist
 
An Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional ParadigmsAn Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional Paradigms
 
Spark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin OderskySpark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin Odersky
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming language
 
Martin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaMartin Odersky - Evolution of Scala
Martin Odersky - Evolution of Scala
 
Scala overview
Scala overviewScala overview
Scala overview
 

Introduction to scala for a c programmer

  • 1.
  • 2. INTRODUCTION TO SCALA PART I BY:- GIRISH KUMAR A L
  • 3. What is SCALA ? 1. Martin Odersky 2. General purpose programming language. 1. It blends in “Object Oriented” and “functional Programming” paradigms. 2. SCALA’s innovations come primarily from how its constructs are put together.
  • 4. What is SCALA ? Functional Programming: Is a programming paradigm where we try to divide programs into functions, which have no side effects i.e. don’t change program state and void mutable data. Eliminating side effects can make it much easier to understand and predict the behavior of a program.
  • 5. What is SCALA ? Object-oriented-programming: Is a programming paradigm where programs are divided into containers called Objects which have data fields and behavior(methods). SCALA is a pure OOP language.
  • 6. SCALA and JAVA SCALA JAVA C++ C 1. SCALA was written keeping in mind that “its impractical” to come-up with a new programming language and make it widely acceptable without interoperating with applications from Java. 2. “Java code can call SCALA code” and “SCALA code can can java code”. Scala gets compiled into Java Byte codes, which gets executed on Java virtual machine.
  • 7. SCALA AND JAVA 1. So, SCALA was written for Java programmers ?. 2. Most of the courses, books and tutorials assume that you already know java or at least OOP. But
  • 8. SCALA for a C language PROGRAMMER.  There is no shortcut here.  First go and learn Java , or at least go here : http://docs.oracle.com/javase/tutorial/java/index.html , and ramp up on Basic OOP concepts.  New and important features of SCALA such as pattern matching, Traits and compositions need OOP concepts.  Even basic language constructs like If-else, for loops, function declarations and definitions, etc. are quite different , and not only with respect to syntax.
  • 9. BUT why SCALA ? 1. A lot of interesting companies like Twitter, Foursquare and LinkedIn are using/adopting SCALA. 1. There are even some VIM plugins around. 2. Good build tool support like SBT, Maven, Ant etc.. 3. SCALA is now in its v2.10. Lot of new features every release. 5. And it is not like IPv4 to IPv6 transformation. It must be fairly easy for java based applications to port to SCALA.
  • 10. 1. SOME attractive features OF scala Variables in SCALA. 1. Variable Immutability. 2. Type inference. 2. Functions in SCALA. 1. Anonymous Functions. 3. SCALA control constructs. 1. If expression. 2. For expression. 4. Pattern Matching. 1. With Constants. 2. With Regular expressions.
  • 11. Variables in SCALA: VAL AND VAR When programming in C, If we want a variable, most of us will be thinking in these steps 1. I need an Integer int
  • 12. VAL AND VAR 1.Let me give it a name “x”, that declares x. This is enough we can go ahead ,but… int x;
  • 13. VAL AND VAR 1. Let me initialize it to 0, to be safe. This defines x(allocates memory) int x = 0;
  • 14. VAL AND VAR In SCALA we will have to think in this way: 1. I need a mutable or a immutable field? i.e. val or var ? Lets go with a val. val
  • 15. VAL AND VAR 2. Let me name it “x”. val x
  • 16. VAL AND VAR 3. OK I need it to be an Integer val x: Int
  • 17. VAL AND VAR 3. Let me initialize it to 0. This ends the value definition. val x: Int = 0 4. But scala has “Type inference” right!? Why do I need to type it as “Int”. Yes we can omit it. Its enough just to have this: val x = 0
  • 18. TYPE inference in SCALA val s = “STRING” var x = (1, “ONE”)
  • 19. Function DEFINITIONS In C int factorial(int x) { if(x == 1) return x; else return x * factorial(x - 1); }
  • 20. Function Definitions • In SCALA • def factorial(x: Int): Int = { if(x == 1) x else x * factorial(x - 1) } • So this function is of type (Important!) • (Int) => Int
  • 21. Function Definitions • If there is no parameter to function! • def function1(): Int = { 255 • } • We can even forget about () and Int!! • def function2 = { • 1+2 • } // These functions are of type () => Int
  • 22. Function Definitions • If the function is not returning anything then we can forget about “=” def function3 { //Body } If the function body is of only one line then we can even forget about “{ }” def function4 = 1
  • 23. FUNCTION LITERALS 1. Also called as Anonymous Functions, these functions are not bound to an identifier. Can be written in below format in SCALA. (x: Int, y:Int) => (x+y) 2. These functions can be passed as arguments to “Higher-order functions”. def higherOrderFunc(f: (Int, Int) => Int) : Int;
  • 24. SCALA IF EXPRESSION It looks similar to if in C, but SCALAS “if” is an expression. So it returns a value. if(!args.isEmpty) args(0) else “default.txt” And it can be used inside function calls, and as function bodies. println(if(!args.isEmpty) args(0) else “default.txt”) OR def function(args: Array[String]): String = if(!args.isEmpty) args(0) else “default.txt”
  • 25. SCALA FOR EXPRESSION For expression in SCALA is the Swiss army knife of iteration. for ( generator definition filter) 1. Iteration through an Array. for (x <- 0 to 100) OR for (x <- 0 until 100) OR just for(x <- args)
  • 26. SCALA FOR EXPRESSION 2. Using Filters for ( x <- 1 to 100 if x%2 == 0) println(x) You can use multiple filters : for { x <-1 to 100 if x%2 == 0 if x%3 == 0 } println(x) for (x <- args if x.matches(“^d*$”)) println(x)
  • 27. SCALA FOR EXPRESSION 3. Using definitions for (x <- args y = x.length if y <= max) println(x) 4 . Multiple Generators: for (x <- args y <- x) println(y) 5. Returning from a for expression using Yield val y = for(x <- 1 to 100 if x%3 == 0) yield x
  • 28. Pattern Matchinga construct called Pattern matching in scala is done with the help of match which looks similar to c language switch. Simple example: pattern matching with constants x match { case “-help” | “-h” => displayHelp case “-version” | “-v” => displayVersion case _ => process }
  • 29. Pattern Matching with Regular expressions A simple example, with regular expressions val regex = "(^d*$)".r def patternMatch(x: String) = x match { case regex(a) => println("matched") case _ => println("Did Not matched") } patternMatch("1234") patternMatch("abcd")
  • 30. KEY DIFFRENCES BETWEEN C AND SCALA Comparable features C SCALA Programming paradigm Imperative programming Functional and object oriented programming Compiler Compiled to machine code Compiled to Byte codes High-level Data-structures No Language support, but libraries are added on Lists[T], Maps[T,M], Set[T], SortedSet[T,M] top using primary data types Concurrency With Help of locks and shared-memory With help of actors, share nothing strategy. But still supports locks and shared-memory. Scripting No scripting support Scripting support Memory management Logic has to be built into the application code to Garbage collector frees memory as soon as it free allocated memory. goes out of scope Pattern Matching No support Pattern matching with help of case classes, regular expressions. Performance Benchmarking Highly optimized C ++ , short run time code is ----------- about 3 times faster. Debuggability / Maintenance Difficult to debug as everything is mutable Much easier to debug as mostly everything can be immutable. Development Longer development time. Most concise language constructs reduce development time and number of lines of code by half compared to Java. Source: Google benchmarks C++, Go, Java and SCALA Performance
  • 31. 1. Other Features of SCALA Singleton Objects. 2. Pattern Matching with case classes. 3. Stackable features with Traits. 4. Companion objects and Factory Methods. 5. Synchronized collections. 6. Concurrent programming with Actors. These and more can be covered in Part II.
  • 32. 1. References Official Scala API database: http://www.scala-lang.org/api/current/index.html#package 2. Programming in SCALA second edition by Martin Odersky 3. Scala Tutorial at http://www.tutorialspoint.com/scala/index.htm
  • 33. Q&A

Editor's Notes

  1. In C we think I need an IntegerLet me name it XLet me initialize it to 0In ScalaI need value/Variable?
  2. In C we think I need an IntegerLet me name it XLet me initialize it to 0In ScalaI need value/Variable?
  3. In C we think I need an IntegerLet me name it XLet me initialize it to 0In ScalaI need value/Variable?
  4. This is where you explain what is a val
  5. This is not enough if it a method local mutable/immutable you need more ?
  6. This is not enough if it a method local mutable/immutable you need more ?
  7. Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  8. Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  9. Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  10. Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  11. Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  12. Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  13. Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  14. Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  15. Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  16. Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  17. Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  18. Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  19. Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  20. Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  21. Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  22. Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  23. Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does