码迷,mamicode.com
首页 > 其他好文 > 详细

Scala学习笔记——内建控制结构

时间:2017-04-04 23:19:51      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:until   抛出异常   org   ==   else   for   rgs   sbt   scala   

Scala的内建控制结构包括:if、while、for、try、match和函数调用

1.if表达式

    //常见的写法
    var filename = "name"
    if (!args.isEmpty)
      filename = args(0)

    //比较简洁的写法
    var filename1 =
      if (!args.isEmpty) args(0)
      else "name"

    //更简洁的写法,不要有中间变量
    println(if(!args.isEmpty) args(0) else "name")

 

2.while循环,while循环和其他语言的一样,有while和do while

  Scala中对再次赋值语句的返回值是Unit,比如下面这个例子

技术分享

 

3.for表达式

    //列出当前目录的文件和文件夹
    val filesHere = (new java.io.File(".")).listFiles

    for (file <- filesHere)
      println(file)

    //打印1到4
    for (i <- 1 to 4)
      println(i)

    //打印1到3
    for (i <- 1 until 4)
      println(i)

    //for循环中的过滤功能
    for (file <- filesHere if file.getName.endsWith("project"))
      println(file)

    //for循环中的过滤功能,多个条件用;号分隔
    for (file <- filesHere
         if file.isFile;
         if file.getName.endsWith("sbt")
    ) println(file)

    //嵌套枚举
    for( a <- 1 to 3; b <- 1 to 3){
      println( "Value of a: " + a );
      println( "Value of b: " + b );
    }

    //for循环采用yield,可以从存储中返回for循环中的变量的值,输出List(1, 2, 4, 5, 6, 7)
    val numList = List(1,2,3,4,5,6,7,8,9,10)
    System.out.println(
      for{
        a <- numList if a != 3; if a < 8
      }yield a
    )

 

4.使用try表达式处理异常

   抛出异常

//抛出异常
  def isEven(n : Int): Unit ={
    val half =
      if (n % 2 == 0) n / 2
      else throw new RuntimeException("n必须是偶数")
  }

   捕获异常,finally语句

  val file = new FileReader("input.txt")
    try {
      //使用文件
    } catch {
      //捕获异常
      case ex: FileNotFoundException =>
      case ex: IOException =>
    } finally {
      //确保文件关闭
      file.close()
    }

   catch子语句的返回值

//try-catch-finally语句的返回值
  def urlFor(path:String) =
    try{
      new URL(path)
    }catch{
      case e:MalformedURIException => new URL("www.scala-lang.org")
    }

  避免使用finally子句返回值

 技术分享

 

5.匹配(match)表达式

  Scala的match表达式类似于switch语句,其中 _ 表示其他的情况

  match表达式中的每一个备选项中break是隐含的,也就是不允许从一个备选项中落到下一个备选项中

    //匹配表达式
    val firstArg = if (args.length > 0) args(0) else ""
    firstArg match {
      case "1" => println("A")
      case "2" => println("B")
      case "3" => println("C")
      case _ => println("D")
    }

 

6.Scala中不再使用break和continue

可以用if替换每个continue,用布尔变量来替换每个break

Scala学习笔记——内建控制结构

标签:until   抛出异常   org   ==   else   for   rgs   sbt   scala   

原文地址:http://www.cnblogs.com/tonglin0325/p/6666622.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!