SlideShare una empresa de Scribd logo
1 de 20
Built-in Control Structures


     Ayush Kumar Mishra
    Sr. Software Consultant
            Knoldus
●
    Scala has only a handful of built-in control structures :
    if, while, for, try, match, and function calls .
●
    The reason Scala has so few is that it has included
    function literals .
●
    A function literal is defined like so:
    scala> val add = (a:Int, b:Int) => a + b
    add: (Int, Int) => Int = <function2>

    scala> add(1,2)
    res1: Int = 3
●
    Almost all of Scala's control structure result in some
     value .

●
    Scala’s built-in control structures act much like their
     imperative equivalents.

●
    But because they tend to result in a value, they
     support a functional style, too.
If Expression
Scala’s if works just like in many other languages.
In Imperative style:
var filename = "default.txt"
if (!args.isEmpty)
filename = args(0)
In Functional Style :
1)val filename =
if (!args.isEmpty) args(0)
else "default.txt"
2)println(if (!args.isEmpty) args(0) else "default.txt")
while and do.. while
●
    Scala’s while and do.. while loop behaves as in other
     languages.
●
    The while and do-while constructs are called “loops,”
     not expressions .
●
    Because the while loop results in no value, it is often
    left out of pure functional languages.
●
     Sometimes an imperative solution can be more
     readable using While Loop . :( But Not
     Recommended .
In Imperative style:
 def gcdLoop(x: Long, y: Long): Long = {
 var a = x
 var b = y
 while (a != 0) {
 val temp = a
 a=b%a
 b = temp}
 b}
– In Functional Style
 def gcd(x: Long, y: Long): Long =
 if (y == 0) x else gcd(y, x % y)
Exception handling with try expressions

  ●
      In Scala exceptions are not checked so effectively all
        exceptions are runtime exceptions.
  ●
      Instead of returning a value in the normal way, a method
        can terminate by throwing an exception.
      Throwing exceptions

  ●
      You create an exception object and then you throw it with
       the throw keyword:
      throw new IllegalArgumentException
●
    An exception throw has type Nothing.
●
    Type Nothing is at the very bottom of Scala’s class
      hierarchy; it is a sub-type of every other type.
●
    In Scala Library , it is defined as :
    def error(message: String): Nothing =
    throw new RuntimeException(message)


    def divide(x: Int, y: Int): Int =
    if (y != 0) x / y
    else error("can't divide by zero")
Catching exceptions


●
    Scala allows you to try/catch any exception in a single block
    and then perform pattern matching against it using case blocks as shown
    below:

    try {
    val f = new FileReader("input.txt")
    // Use and close file
    } catch {
    case ex: FileNotFoundException => // Handle missing file
    case ex: IOException => // Handle other I/O error
    }
The finally clause


●
    The finally clause can contain code that you need to be executed,
    no matter if an exception is thrown or not.
    val file = new FileReader("input.txt")
    try {
    // Use the file
    } finally {
    file.close()
    // Be sure to close the file
    }
Yielding a value


●
    As with most other Scala control structures, try-catch-finally results in
    a value .

    def urlFor(path: String) =
    try {
    new URL(path)
    } catch {
    case e: MalformedURLException =>
    new URL("http://www.scala-lang.org")
    }
Match expressions


●   Scala’s match expression lets you select from a number of
     alternatives, just like switch statements in other languages.


    val firstArg = if (args.length > 0) args(0) else ""
    firstArg match {
    case "salt" => println("pepper")
    case "chips" => println("salsa")
    case "eggs" => println("bacon")
    case _ => println("huh?")
    }
–
Living without break and continue
●
     The simplest approach is to replace every continue by an if and every
     break by a boolean variable.
    int i = 0;
    // This is Java
    boolean foundIt = false;
    while (i < args.length) {
    if (args[i].startsWith("-")) {i = i + 1;
    continue;}
    if (args[i].endsWith(".scala")) {foundIt = true;
    break;
    }i = i + 1;}
In Scala :                        In Functional Style :
var i = 0
                                  def searchFrom(i: Int): Int =
var foundIt = false
                                  if (i >= args.length) -1
while (i < args.length && !
  foundIt) {                      else if (args(i).startsWith("-"))
if (!args(i).startsWith("-")) {      searchFrom(i + 1)
if (args(i).endsWith(".scala"))
                                  else if
foundIt = true                       (args(i).endsWith(".scala")) i
}
                                  else searchFrom(i + 1)
i=i+1
}                                 val i = searchFrom(0)
Still Want to use Break ? :(
    ●
        In Scala’s standard library. Class Breaks in package
          scala.util.control offers a break method .

            breakable {
                 while (true) {
                        println("hiii ")
                        if (in.readLine() == "") break
                 }
            }
        –
For expressions


●   It can result in an interesting value, a collection whose
    type is determined by the for expression’s <- clauses.

●   for ( seq ) yield expr
    seq is a sequence of generators, definitions, and filters .
    Ex: for {
                 p <- persons // a generator
                 n = p.name // a definition
                 if (n startsWith "To") // a filter
          }
Filtering:-
        filter: an if clause inside the for’s parentheses.
        val filesHere = (new java.io.File(".")).listFiles
        for (file <- filesHere if file.getName.endsWith(".scala") )
        println(file)
Producing a new collection:-
        Prefix the body of the for expression by the keyword yield.
        for clauses yield body
to find the titles of all books whose author’s last name is “Gosling”:
        scala> for (b <- books; a <- b.authors
        if a startsWith "Gosling")
        yield b.title
        res4: List[String] = List(The Java Language Specification)
Translation of for expressions
    Every for expression can be expressed in terms of the three higher-order
     functions
●   Map
●   FlatMap
●   withFilter.
    Translating for expressions with one generator
    for (x <- expr1 ) yield expr2   is translated to
    expr1 .map(x => expr2 )


    Translating for expressions starting with a generator and a filter
    for (x <- expr1 if expr2 ) yield expr3 is translated to:
    for (x <- expr1 withFilter (x => expr2 )) yield expr3
    finally
    expr1 withFilter (x => expr2 ) map (x => expr3 )




–
Translating for expressions starting with two generators


    for (x <- expr1 ; y <- expr2 ; seq) yield expr3
    is translated to
    expr1 .flatMap(x => for (y <- expr2 ; seq) yield expr3 )
    Ex:-
    for (b1 <- books; b2 <- books if b1 != b2;
           a1 <- b1.authors; a2 <- b2.authors if a1 == a2)
                  yield a1
    This query translates to the following map/flatMap/filter combination:
    books flatMap (b1 =>
           books withFilter (b2 => b1 != b2) flatMap (b2 =>
                  b1.authors flatMap (a1 =>
                  b2.authors withFilter (a2 => a1 == a2) map (a2 =>
                  a1))))
•
Thank You

Más contenido relacionado

La actualidad más candente

Java Collections
Java CollectionsJava Collections
Java Collections
parag
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scala
akuklev
 

La actualidad más candente (20)

Java Tutorial Lab 4
Java Tutorial Lab 4Java Tutorial Lab 4
Java Tutorial Lab 4
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
Java Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6
 
Learn ActionScript programming myassignmenthelp.net
Learn ActionScript programming myassignmenthelp.netLearn ActionScript programming myassignmenthelp.net
Learn ActionScript programming myassignmenthelp.net
 
Understanding the components of standard template library
Understanding the components of standard template libraryUnderstanding the components of standard template library
Understanding the components of standard template library
 
L11 array list
L11 array listL11 array list
L11 array list
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVA
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
 
Covariance & Contravariance
Covariance &  ContravarianceCovariance &  Contravariance
Covariance & Contravariance
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
Scala test
Scala testScala test
Scala test
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scala
 
Collections - Sorting, Comparing Basics
Collections - Sorting, Comparing Basics Collections - Sorting, Comparing Basics
Collections - Sorting, Comparing Basics
 

Similar a Knolx Session : Built-In Control Structures in Scala

(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
Tomasz Wrobel
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 

Similar a Knolx Session : Built-In Control Structures in Scala (20)

Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Scala basic
Scala basicScala basic
Scala basic
 
Python to scala
Python to scalaPython to scala
Python to scala
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
Introductiontoprogramminginscala
 
Ruby Basics
Ruby BasicsRuby Basics
Ruby Basics
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Scala training workshop 02
Scala training workshop 02Scala training workshop 02
Scala training workshop 02
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
 
Scala presentationjune112011
Scala presentationjune112011Scala presentationjune112011
Scala presentationjune112011
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 
Practically Functional
Practically FunctionalPractically Functional
Practically Functional
 
Java Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsJava Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, Assertions
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
2014 holden - databricks umd scala crash course
2014   holden - databricks umd scala crash course2014   holden - databricks umd scala crash course
2014 holden - databricks umd scala crash course
 
Scala - just good for Java shops?
Scala - just good for Java shops?Scala - just good for Java shops?
Scala - just good for Java shops?
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala Makeover
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In Scala
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 

Knolx Session : Built-In Control Structures in Scala

  • 1. Built-in Control Structures Ayush Kumar Mishra Sr. Software Consultant Knoldus
  • 2. Scala has only a handful of built-in control structures : if, while, for, try, match, and function calls . ● The reason Scala has so few is that it has included function literals . ● A function literal is defined like so: scala> val add = (a:Int, b:Int) => a + b add: (Int, Int) => Int = <function2> scala> add(1,2) res1: Int = 3
  • 3. Almost all of Scala's control structure result in some value . ● Scala’s built-in control structures act much like their imperative equivalents. ● But because they tend to result in a value, they support a functional style, too.
  • 4. If Expression Scala’s if works just like in many other languages. In Imperative style: var filename = "default.txt" if (!args.isEmpty) filename = args(0) In Functional Style : 1)val filename = if (!args.isEmpty) args(0) else "default.txt" 2)println(if (!args.isEmpty) args(0) else "default.txt")
  • 5. while and do.. while ● Scala’s while and do.. while loop behaves as in other languages. ● The while and do-while constructs are called “loops,” not expressions . ● Because the while loop results in no value, it is often left out of pure functional languages. ● Sometimes an imperative solution can be more readable using While Loop . :( But Not Recommended .
  • 6. In Imperative style: def gcdLoop(x: Long, y: Long): Long = { var a = x var b = y while (a != 0) { val temp = a a=b%a b = temp} b} – In Functional Style def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)
  • 7. Exception handling with try expressions ● In Scala exceptions are not checked so effectively all exceptions are runtime exceptions. ● Instead of returning a value in the normal way, a method can terminate by throwing an exception. Throwing exceptions ● You create an exception object and then you throw it with the throw keyword: throw new IllegalArgumentException
  • 8. An exception throw has type Nothing. ● Type Nothing is at the very bottom of Scala’s class hierarchy; it is a sub-type of every other type. ● In Scala Library , it is defined as : def error(message: String): Nothing = throw new RuntimeException(message) def divide(x: Int, y: Int): Int = if (y != 0) x / y else error("can't divide by zero")
  • 9. Catching exceptions ● Scala allows you to try/catch any exception in a single block and then perform pattern matching against it using case blocks as shown below: try { val f = new FileReader("input.txt") // Use and close file } catch { case ex: FileNotFoundException => // Handle missing file case ex: IOException => // Handle other I/O error }
  • 10. The finally clause ● The finally clause can contain code that you need to be executed, no matter if an exception is thrown or not. val file = new FileReader("input.txt") try { // Use the file } finally { file.close() // Be sure to close the file }
  • 11. Yielding a value ● As with most other Scala control structures, try-catch-finally results in a value . def urlFor(path: String) = try { new URL(path) } catch { case e: MalformedURLException => new URL("http://www.scala-lang.org") }
  • 12. Match expressions ● Scala’s match expression lets you select from a number of alternatives, just like switch statements in other languages. val firstArg = if (args.length > 0) args(0) else "" firstArg match { case "salt" => println("pepper") case "chips" => println("salsa") case "eggs" => println("bacon") case _ => println("huh?") } –
  • 13. Living without break and continue ● The simplest approach is to replace every continue by an if and every break by a boolean variable. int i = 0; // This is Java boolean foundIt = false; while (i < args.length) { if (args[i].startsWith("-")) {i = i + 1; continue;} if (args[i].endsWith(".scala")) {foundIt = true; break; }i = i + 1;}
  • 14. In Scala : In Functional Style : var i = 0 def searchFrom(i: Int): Int = var foundIt = false if (i >= args.length) -1 while (i < args.length && ! foundIt) { else if (args(i).startsWith("-")) if (!args(i).startsWith("-")) { searchFrom(i + 1) if (args(i).endsWith(".scala")) else if foundIt = true (args(i).endsWith(".scala")) i } else searchFrom(i + 1) i=i+1 } val i = searchFrom(0)
  • 15. Still Want to use Break ? :( ● In Scala’s standard library. Class Breaks in package scala.util.control offers a break method . breakable { while (true) { println("hiii ") if (in.readLine() == "") break } } –
  • 16. For expressions ● It can result in an interesting value, a collection whose type is determined by the for expression’s <- clauses. ● for ( seq ) yield expr seq is a sequence of generators, definitions, and filters . Ex: for { p <- persons // a generator n = p.name // a definition if (n startsWith "To") // a filter }
  • 17. Filtering:- filter: an if clause inside the for’s parentheses. val filesHere = (new java.io.File(".")).listFiles for (file <- filesHere if file.getName.endsWith(".scala") ) println(file) Producing a new collection:- Prefix the body of the for expression by the keyword yield. for clauses yield body to find the titles of all books whose author’s last name is “Gosling”: scala> for (b <- books; a <- b.authors if a startsWith "Gosling") yield b.title res4: List[String] = List(The Java Language Specification)
  • 18. Translation of for expressions Every for expression can be expressed in terms of the three higher-order functions ● Map ● FlatMap ● withFilter. Translating for expressions with one generator for (x <- expr1 ) yield expr2 is translated to expr1 .map(x => expr2 ) Translating for expressions starting with a generator and a filter for (x <- expr1 if expr2 ) yield expr3 is translated to: for (x <- expr1 withFilter (x => expr2 )) yield expr3 finally expr1 withFilter (x => expr2 ) map (x => expr3 ) –
  • 19. Translating for expressions starting with two generators for (x <- expr1 ; y <- expr2 ; seq) yield expr3 is translated to expr1 .flatMap(x => for (y <- expr2 ; seq) yield expr3 ) Ex:- for (b1 <- books; b2 <- books if b1 != b2; a1 <- b1.authors; a2 <- b2.authors if a1 == a2) yield a1 This query translates to the following map/flatMap/filter combination: books flatMap (b1 => books withFilter (b2 => b1 != b2) flatMap (b2 => b1.authors flatMap (a1 => b2.authors withFilter (a2 => a1 == a2) map (a2 => a1)))) •