SlideShare uma empresa 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

Mais conteúdo relacionado

Mais procurados

Java Tutorial Lab 4
Java Tutorial Lab 4Java Tutorial Lab 4
Java Tutorial Lab 4Berk Soysal
 
Java Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6Berk Soysal
 
Learn ActionScript programming myassignmenthelp.net
Learn ActionScript programming myassignmenthelp.netLearn ActionScript programming myassignmenthelp.net
Learn ActionScript programming myassignmenthelp.netwww.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 libraryRahul Sharma
 
L11 array list
L11 array listL11 array list
L11 array listteach4uin
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets Hitesh-Java
 
Java Collections
Java CollectionsJava Collections
Java Collectionsparag
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVASAGARDAVE29
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaEdureka!
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++•sreejith •sree
 
Covariance & Contravariance
Covariance &  ContravarianceCovariance &  Contravariance
Covariance & ContravarianceMesh Korea
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections frameworkRiccardo Cardin
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scalaakuklev
 
Collections - Sorting, Comparing Basics
Collections - Sorting, Comparing Basics Collections - Sorting, Comparing Basics
Collections - Sorting, Comparing Basics Hitesh-Java
 

Mais procurados (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
 

Semelhante a BUILT-IN CONTROL STRUCTURES

Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
IntroductiontoprogramminginscalaAmuhinda Hungai
 
(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
 
Scala training workshop 02
Scala training workshop 02Scala training workshop 02
Scala training workshop 02Nguyen Tuan
 
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 ScalaDerek Chen-Becker
 
Practically Functional
Practically FunctionalPractically Functional
Practically Functionaldjspiewak
 
Java Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsJava Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsAnton Keks
 
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 courseHolden Karau
 
Scala - just good for Java shops?
Scala - just good for Java shops?Scala - just good for Java shops?
Scala - just good for Java shops?Sarah Mount
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala MakeoverGarth Gilmour
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In ScalaSkills Matter
 
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 DevelopersMiles Sabin
 

Semelhante a BUILT-IN CONTROL STRUCTURES (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

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 

Último (20)

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 

BUILT-IN CONTROL STRUCTURES

  • 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)))) •