Scala深入学习之表达式与循环学习

目录

    • 一、表达式
      • (1)表达式
      • (2)条件表达式
      • (3)块表达式
    • 二、循环
      • (1)for循环
      • (2)高级for循环
      • (3)for推导
      • (4)while do-while循环
      • (5)if和布尔变量跳出循环
      • (6)breakable实现跳出循环

一、表达式

(1)表达式

表达式:一个具有执行结果的代码块,结果是具体的值或者()
表达式和语句的区别:

  • 表达式有返回值,语句被执行。表达式一般是一个语句块,执行后,返回一个值。
  • 不使用return语句,最后一个表达式即返回值。

示例:

// 返回的就是string类型
scala> val res = if(true) "true result" else "false result"
res: String = true result

scala> val res = if(true) println("true result") else "false result"
true result
res: Any = ()

scala> var a = 1
a: Int = 1
// 返回的是Any
scala> val res = if(true) a+=10 else "false result"
res: Any = ()
// Scala表达式中不使用return语句
scala> val res = if(true) return "true result" else return "false result"
<console>:11: error: return outside method definition
       val res = if(true) return "true result" else return "false result"
                          ^
<console>:11: error: return outside method definition
       val res = if(true) return "true result" else return "false result"
                                                    ^

(2)条件表达式

单分支
基本语法:if(条件表达式){执行代码块},说明当条件表达式为true,就会执行{}的代码

scala> val x = 10
x: Int = 10
// 这里会有同学问,为什么返回的是AnyVal类型,不是Int类型
scala> val res = if(x>0) 1
res: AnyVal = 1
// 解释:上一行表达式等价于下一行的写法,else返回的是unit类型,所以结果返回的就是AnyVal
scala> val res = if(x>0) 1 else ()
res: AnyVal = 1

双分支
基本语法:if(条件表达式){执行代码块1}else{执行代码块1}
说明当条件表达式成立,即执行代码块1,否则执行代码块2

scala> val res1 = if( x>0 ) 1 else -1
res1: Int = 1

多分支
基本语法:if(条件表达式1){执行代码块1}
else if(条件表达式2){执行代码块2}
else {执行代码块n}

scala> val res2 = if(x>0) 10 else if(x<0) -1 else 0
res2: Int = 10
// 混合类型,就会返回Any类型
scala> val res2 = if(x>0) 10 else if(x<0) -1 else "failure"
res2: Any = 10

注意:

  • 每个表达式都有一个类型
  • 条件表达式都有值
  • 混合类型表达式,结果是Any或AnyVal
  • Scala没有switch语句

(3)块表达式

块表达式:{一条或者多条语句},块表达式也是有返回值
返回值是块表达式中的最后一条语句的结果,最后一条语句是打印语句或赋值语句,返回值就是一个()

package expr

/**
 * @author : 蔡政洁
 * @email :[email protected]
 * @date : 2020/8/18
 * @time : 1:38 下午
 */
object BlockExpr {
  def main(args: Array[String]): Unit = {
    // 块表达式1
    val x = 0
    val res1 = {
      if (x<0) 1
      else if(x>=0) -1
      else "error"
    }
    println(res1)

    // 块表达式2
    val x1 = 1
    val x2 = 2
    val y1 = 1
    val y2 = 2

    val distance = {
      val dx = x2-x1
      val dy = y2-y1
      Math.sqrt(dx*dx+dy*dy)
    }
    println(distance)
  }
}
-1
1.4142135623730951

二、循环

(1)for循环

Scala中有for循环和while循环,用for循环比较多
for循环语法结构:for (i <- 表达式/数组/集合)
to和until

  • i to j (包含i和j)
  • i until j (包含i,但不包含j)
package forDemo

/**
 * @author : 蔡政洁
 * @email :[email protected]
 * @date : 2020/8/18
 * @time : 6:50 下午
 */
object ForDemo1 {
  def main(args: Array[String]): Unit = {
    // 每次从集合中取一个值,赋值给循环变量
    for (i <- 1 to 10){
      println(i)
    }
    // 循环遍历一个数组
    val arr = Array("a","b","c","d")
    for (item <- arr){
      println(item)
    }
  }
}

运行结果:

1
2
3
4
5
6
7
8
9
10
a
b
c
d

(2)高级for循环

package forDemo

/**
 * @author : 蔡政洁
 * @email :[email protected]
 * @date : 2020/8/18
 * @time : 6:55 下午
 */
object ForDemo2 {
  // 循环的嵌套以及带守卫的循环
  def main(args: Array[String]): Unit = {
    // 循环嵌套
    for (i <- 1 to 3; j <- 1 to 3){
      println(10*i + j)
    }
    // 等价于
    println("----------等价于----------")
    for (i <- 1 to 3){
      for (j <- 1 to 3){
        println(10*i + j)
      }
    }
    // 带守卫的循环
    println("----------带守卫的循环----------")
    for (i <- 1 to 3; j <- 1 to 3 if i != 3){
      println(10*i + j)
    }
  }
}

运行结果:

11
12
13
21
22
23
31
32
33
----------等价于----------
11
12
13
21
22
23
31
32
33
----------带守卫的循环----------
11
12
13
21
22
23

(3)for推导

for推导,yield
通过yield开始的循环,叫for推导,会构建一个新的集合,新集合中的元素是遍历for循环中的集合,每次根据yield后面的表达式生成一个新的元素

package forDemo

/**
 * @author : 蔡政洁
 * @email :[email protected]
 * @date : 2020/8/18
 * @time : 7:03 下午
 */
object ForDemo3 {
  // for推导,yield
  def main(args: Array[String]): Unit = {
    // 通过yield开始的循环,叫for推导,会构建一个新的集合,新集合中的元素是遍历for循环
    // 中的集合,每次根据yield后面的表达式生成一个新的元素
    val result = for (i <- 0 until 10) yield i*10
    println(result)
  }
}

运行结果:

Vector(0, 10, 20, 30, 40, 50, 60, 70, 80, 90)

(4)while do-while循环

package whileDemo

/**
 * @author : 蔡政洁
 * @email :[email protected]
 * @date : 2020/8/18
 * @time : 7:20 下午
 */
object WhileDoWhileDemo {
  def main(args: Array[String]): Unit = {
    // 使用while完成求和(1,2,3,。。10)
    var i = 1
    var sum = 0
    while (i <= 10){
      sum += i
      i += 1
    }
    println(sum)
    // 使用do while完成求和(1,2,3,。。10)
    do {
      sum += i
      i += 1
    } while (i <= 10)
    println(sum)
  }
}

(5)if和布尔变量跳出循环

package whileDemo

/**
 * @author : 蔡政洁
 * @email :[email protected]
 * @date : 2020/8/18
 * @time : 7:26 下午
 */
object ContinueDemo {
  def main(args: Array[String]): Unit = {
    // 数组("aa.scala","-bb.java","cc.scala","dd.java","-ee.scala")
    // 查找以".scala"结尾但是不以"-"开始的的字符串
    val arr = Array("aa.scala","-bb.java","cc.scala","dd.java","-ee.scala")
    // 实现break功能
    var found = false
    var i = 0
    while (i < arr.length && !found){
      // 实现continue功能
      if(!arr(i).startsWith("-")){
        if (arr(i).endsWith(".scala")){
          found = true
          println(arr(i))
        }
      }
      i += 1
    }
  }
}

运行结果:

aa.scala

(6)breakable实现跳出循环

第五点可以通过if来实现continue功能,通过加一个布尔变量来实现break功能,同时也可以使用breakable关键字。在使用breakable之前要import scala.util.control.Breaks._

package whileDemo

import scala.util.control.Breaks._

/**
 * @author : 蔡政洁
 * @email :[email protected]
 * @date : 2020/8/18
 * @time : 7:46 下午
 */
object BreakableDemo {
  def main(args: Array[String]): Unit = {
    // 实现break的功能,如果i=5,终止循环
    breakable(
      for (i <- 0 until 10){
        if (i == 5){
          break()
        }
        println(i)
      })

    println("----------------------")
    // 实现continue的功能,如果i=5,终止本次循环
    for (i <- 0 until 10) breakable({
      if (i == 5){
        break()
      }
      println(i)
    })
  }
}

运行结果:

0
1
2
3
4
----------------------
0
1
2
3
4
6
7
8
9

以上内容仅供参考学习,如有侵权请联系我删除!
如果这篇文章对您有帮助,左下角的大拇指就是对博主最大的鼓励。
您的鼓励就是博主最大的动力!

你可能感兴趣的:(Scala学习指南)