Scala学习笔记-2-(if、while、for、try、match)

if

Scala 中的 if 也有返回值,最后一个表达式的结果就是返回值

while

Scala 中并不推荐使用循环,而是推荐使用递归函数
while 和 do...while 称为循环而不是表达式,因为他们没有返回值,或者说他们的返回值是 Unit
Unit 可以写成()

for

for 循环的对象是一个生成器 (generator)
常用跳出循环的方法

try

try 和 catch 都有返回值,但是 finally 没有返回值(除非强行加上 return 语句)

match

Scala 中没有 break 和 continue (如果一定要用,可以在 scala.util.control 找到,但是实现机制是通过抛异常,不推荐使用)
一般通过条件判断实现这两个功能,例如循环条件中增加一个 boolean 值
或者用方法递归,不要用循环

没有 break 和 continue

源代码

package day03

class Demo {

}

object Demo {

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

    doIf(args)

    doWhile(args)

    doFor(args)

    doTry(args)

    doMatch(args)

    test(args);
  }

  /**
    * Scala 中的 if 也有返回值,最后一个表达式的结果就是返回值
    *
    * @param args
    */
  def doIf(args: Array[String]): Unit = {

    // 传统风格
    var filename_1 = "default.txt"
    if (!args.isEmpty)
      filename_1 = args(0)
    println(filename_1)

    // Scala风格
    val filename_2 = if (!args.isEmpty)
      args(0)
    else
      "default.txt"
    println(filename_2)
  }

  /**
    * Scala 中并不推荐使用循环,而是推荐使用递归函数
    * while 和 do...while 称为循环而不是表达式,因为他们没有返回值
    * 或者说他们的返回值是 Unit
    * Unit 可以写成()
    *
    * @param args
    */
  def doWhile(args: Array[String]): Unit = {

    var count = 100

    while (count > 50) {
      count -= 1
      // ...
    }

    do {
      // ...
      count -= 1
    } while (count > 0)
  }

  /**
    * for 循环的对象是一个生成器 (generator)
    *
    * @param args
    */
  def doFor(args: Array[String]): Unit = {

    // 常用循环方案
    for (i <- 1 to 100) {
        println(i)
        // 一般通过修改循环判断条件来提前结束循环
        if (i == 50) i = 200
    }

    // 基本使用
    val filesHere = new java.io.File(".").listFiles
    for (file <- filesHere)
      println(file)

    // 添加条件过滤
    for (
      file <- filesHere
      if file.isFile
      if file.getName.endsWith("scala")
    )
      println(file)

    // 绑定中间变量,使用{}
    for {
      file <- filesHere
      if file.isFile
      name = file.getName
      if name.endsWith("scala")
    }
      println(file)
    // 绑定中间变量,使用()
    for (
      file <- filesHere
      if file.isFile;
      name = file.getName
      if name.endsWith("scala")
    )
      println(file)

    // 多重迭代,注意两个迭代之间需要加上分号(;)因为 Scala 编译器不推算包含在()的省掉的;
    val is = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
    for (
      file <- filesHere;
      i <- is
    )
      println(file + "  " + i)

    // 换用{}
    for {
      file <- filesHere
      i <- is
    }
      println(file + "  " + i)

    // 生成新集合
    val scalaFiles = for {
      file <- filesHere
      if file.isFile
      name = file.getName
      if name.endsWith("scala")
    } yield file
    println(scalaFiles)
  }

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

    try {
      throw new IllegalArgumentException
    } catch {
      case e: IllegalArgumentException => println(e)
    } finally {
      // ...
    }

    // 通常情况下,finally 块用来做些清理工作,而不应该产生结果
    // 这里结果是1
    def g(): Int = try 1 finally 2

    // 如果在 finally 块中使用 return 来返回某个值,这个值将覆盖 try-catch 产生的结果
    // 这里结果是2
    def f(): Int = try {
      1
    } finally {
      return 2
    }
  }

  /**
    * scala 的 match 表达式有返回值
    *
    * @param args
    * @return
    */
  def doMatch(args: Array[String]): String = {

    val firstArg = if (args.length > 0) args(0) else ""
    val friend = firstArg match {
      case "salt" => "pepper"
      case "chips" => "salsa"
      case "eggs" => "bacon"
      case _ => "huh?"
    }
    friend
  }

  /**
    * Scala 中没有 break 和 continue
    * 可以使用替换条件,例如循环条件中增加一个 boolean 值
    * Scala 不推荐使用循环,最好用递归
    *
    * @param args
    */
  def test(args: Array[String]): Unit = {

    var i = 0
    var foundIt = false
    while (i < args.length && !foundIt) {
      // 实现 continue 的功能
      if (args(i).startsWith("Test")) {
        // 实现 break 的功能
        if (args(i).endsWith(".scala")) {
          foundIt = true
        }
      }
      i += 1
    }
  }
}

posted @ 2019-10-14 14:22  飞_2016  阅读(239)  评论(0编辑  收藏  举报