scala programming (seven) - Built-in control structures

Almost all of Scala's control structures will have a certain value. This embodiment is used in a functional language, the program is seen as calculated activity value, so the control program should do. In addition, the command language often has a ternary operator (such as C, C ++ and Java are :? Operator), behave as if, but produce value. Scala ternary operator using this model, but it is called if. In other words, Scala's if the value may be generated. So Scala continued this trend allows for, the try and match also produced value.

if expression

Scala's if the same work as many other languages. It tests a status data and whether it is true, performing one of the two branches, and to return the value of the branch.

def main(args: Array[String]): Unit = {
    val filename =
      if (!args.isEmpty) args(0)
      else "default.txt"

    println(filename)
  }

if have two branches: If args is not empty, then initialize elements, args (0), is selected. Otherwise, the default value is selected. The if expression produces a selected value, then the filename variable is initialized to this value. This code is shorter a little, but its practical advantage is the use of val instead var . Use val is a functional style, and are able to about the same and the Java help you the same final variable way. It allows code readers that this variable will never change, save all the code they scan a variable field to see if it changed the work.

Use val instead of var second point advantage is that he can better support equivalent inference: equational Reasoning . Expression under the premise of no side effects, is equivalent to calculating variables into its expression . Therefore, whenever they can replace the variable name expression. For example, to replace println (f ilename), you could write: println (IF (args.isEmpty) args (0) the else "default.txt"!) The choice is yours. How to write anything. Use val can help you safely perform this type of innovation in order to reconstruct your code.

As far as possible seek to use the opportunity val. They both make your code easier to read and easy to reconstruct.

 

while loop

while, and do-while structure is referred to "cycle " is not an expression, because they do not produce meaningful results, the result is the type Unit. DESCRIPTION value generated (and, indeed, unique value) of type Unit. It is called unit value, written as (). () Presence is Scala's Unit differs from Java in place of the void.

  def main(args: Array[String]): Unit = {
    def greet() = println("hello")
    println(greet() == ())
  }

Print results:

hello
true

Since there is no method body before the equal sign, the greet the result is defined as a type of Unit process. Thus, the greet return the unit value (). This is confirmed the next line: comparison greet results and the unit value equality (), resulting in true.

Another generation architecture related to this unit value is then assigned var, it will return () type.

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

    var content = ""
   println((content = StdIn.readLine()) == ())
   println((content = StdIn.readLine()) == ())
  }

Here's readLine function does not return as it reads from the control to the content, but always returns () That unit type like Java.

Hello first input, a second input an empty string, two results are true;

 

for expression

Scala's for expression is prepared for the enumeration of "Swiss Army knife ." It allows you to use different ways to the combination of a few simple ingredients to express a wide range of enumeration. The simplest usage such as the completion of the sequence of integers enumeration again as usual tasks. More advanced expression can include a plurality of different types of collections, filtering elements may be used in any conditions, can also create new collections.

1) Class enumerations

 

def main(args: Array[String]): Unit = {
    val array = Array(1,2,3,4,5)
    for(elem <- array)
      println(elem)
  }

Printing is as follows:

1
2
3
4
5

In doing so, your code becomes shorter and avoid a lot of super-bit frequently occur when an enumerated array overflow: OFF-by-One error. From the or from the Start 0 1 starts? It should be added to -1, +1, or nothing at all until the last index? These questions are easy to answer, but it is also very easy wrong answer. Avoid touching or better.

2) Filter

Sometimes you do not want to enumerate the elements of a collection class. But I want to filter out a subset. You can filter by: a: filter IF clause added to do for the brackets. If you wish, you can include more filters. Just keep clause can be added. If you added more than one filter in the generator, IF clause must be separated by semicolons.

  def main(args: Array[String]): Unit = {
    val array = Array(1,2,3,4,5,6,7,8,9,10)
    for(elem <- array if(elem>5);if(elem%2 == 0))
      println(elem)
  }

Print results:

6
8
10

3) create new collections

You can also create a value to remember every iteration. As long as the plus before for expression keywords yield. Format is as follows:

for (expression) expression yield {}; and finally returns the results of the tabular yield.

When the time for completion of the expression, the result will be a set containing all the values produced. Result type collection of collections based on the type of enumeration process clause.

Examples are as follows:

def main(args: Array[String]): Unit = {
    val array = Array(1,2,3,4,5,6,7,8,9,10)
    val  elems: Array[String] =
      for(elem <- array if(elem>5);if(elem%2 == 0))
      yield elem.toString

    elems.foreach(println)
  }

Print Results:

6
8
10

 

Try using expressions to handle exceptions

 

Like Scala anomalies and many other languages. Instead a conventional manner, as a return value, a method may abort by throwing. Caller of the method can either catch and handle the exception, or you can simply suspend off, and the abnormal upgrade to the caller caller. It's that exception can upgrade, release layers of the call stack, until some other way to approach to the rest of it or not.

1) throw an exception

The exception thrown and look exactly the same in Java. First, create an exception object and then throw keyword Throws:

throw new IllegalArgumentException

In Scala, throw also a result of the type of expression

def main(args: Array[String]): Unit = {
    val n = 1;
    val half =
      if (n % 2 == 0)
        n / 2
      else
        throw new RuntimeException("n must be even")

    println("hello"+half)
  }

Happens here is that if n is even, Half will be initialized to one half of n. If n is not even, then the exception will be thrown before the half can be initialized to any value. Therefore, no matter how hard the exceptions thrown as a value of any type are safe. From using any attempt to return the value of the throw will not work, so do it harmless.

From a technical point of view, the type of exception is thrown Nothing. Despite the throw does not draw any practical value, you can still treat it as an expression. Such tips may seem weird, but as in the example above, this actually is often useful. a branch if the calculated value, and the other thrown derived Nothing. Whole type if the type of expression is a branch of the actual calculated value.

Print results are as follows:

Exception in thread "main" java.lang.RuntimeException: n must be even

This also

Description: When the exception is not caught, the code will not be executed after the exception;

2) exception is caught

behavioral try-catch expression is consistent with other language exception handling. Body program to be executed, if an exception is thrown, each catch clause in turn is attempted. In the present embodiment, if the exception is a FileNotFoundException, then the first clause is executed. If IOException type, the second clause is executed. If not, then the try-catch will end and the abnormal rise out.

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

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

Print results are as follows:

file not found

With a difference of Java is in Scala does not require you to capture abnormalities: the checked Exception, or declare them in throws clause

 

If you want some code no matter what method should suspend execution, you can put an expression on the finally clause. For example, you may want to open a file even if the method throws an exception must also ensure that exits are closed.

And most other Scala as control structures, the try-value of the catch-the finally also produced. For example, the code shows how to try to split the URL, but if the URL is malformed default value is used. As a result, if no exception is thrown, then the corresponding try clause; throws an exception if and captured, corresponding to the respective catch clause. If an exception is thrown but not caught, the expression would be no return value. The obtained value calculated finally clause, if any, be abandoned. Usually do some type of cleanup work finally clause such as closing files; they should not be changed in the main body of the function or try the catch value calculated clause.

 

object Demo8 {

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


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

    val s = "abc";
    val url = urlFor(s)
    println(url)
  }
}

Print results:

http://www.scalalang.org

 

match expression

Scala matching expressions allow you many options: alternative choice to do, as if a switch statement in other languages. Generally speaking match expression lets you use any patterns: pattern to choose.

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

    val firstArg = "salt"
    firstArg match {
      case "salt" => println("pepper")
      case "chips" => println("salsa")
      case "eggs" => println("bacon")
      case _ => println("huh?")
    }
  }

Print results:

pepper

 

And Java's switch statement than that, there are some important differences in matching expressions. One of them is any kind of constant, or something else, it can be used as Scala in the case, not just the Java case statement inside the integer types, and enumeration constants. In this example, the option is a string. Another difference is that at the end of each of the alternatives did not break. Instead, BREAK is implied, will not be transferred from one situation to another option to go inside. This code is usually shorter, and avoid the source of errors, negligence because the programmer no longer turn to the options in turn go.

And Java are compared to the most significant difference switch, perhaps the match expression can produce values.

 def main(args: Array[String]): Unit = {
    val firstArg = "salt"
    val friend =
      firstArg match {
        case "salt" => "pepper"
        case "chips" => "salsa"
        case "eggs" => "bacon"
        case _ => "huh?"
      }
    println(friend)
  }

Print results

pepper

 

 

 

Guess you like

Origin www.cnblogs.com/chxyshaodiao/p/12342288.html