4.scala基础二(控制结构)

概述

scala和java有差不多的控制结构,可以对比着学习相同与不同点

scala具有编程语言中基本控制结构,包括:

  • if/then/else
  • for loops
  • try/catch/finally

当然也有些不同点:

  • match expressions
  • for expressions

相关链接

scala 相关文章,可以先行浏览

scala相关文章链接

IF/THEN/ELSE 结构

代码
// 和java基本类似
// 基本 if
if (a == b) doSomething()

// 也可以带括号
if (a == b) {
    doSomething()
}

// if/else
if (a == b) {
    doSomething()
} else {
    doSomethingElse()
}

// 完整的Scala if/else-if/else表达式如下
if (test1) {
    doX()
} else if (test2) {
    doY()
} else {
    doZ()
}

if表达式总是返回结果

scala语言的if总是返回结果,可以将结果赋值给变量,这将不需要特殊的三元操作符

val minValue = if (a < b) a else b

面向表达式编程

// As a brief note about programming in general, when every expression you write returns a value, that style is referred to as expression-oriented programming, or EOP. This is an example of an expression:
// 官方说当编写的代码都有一个返回值,这是面向表达编程,称为 EOP
val minValue = if (a < b) a else b

对于不返回值的代码,称之为语句,看下面代码

object IfExp {

  def doSomething() = {

  }

  def main(args: Array[String]): Unit = {
    val a = "c"
    val b = "c"
    if (a == b) doSomething()
    println("Hello")
  }
}

循环

代码
// 创建一个集合,直接命令行操作
// 类型Seq[Int]
val nums = Seq(1,2,3)
for(n <- nums) println(n)

执行示例

scala> val nums = Seq(1,2,3)
nums: Seq[Int] = List(1, 2, 3)

scala> for(n <- nums) println(n)
1
2
3

scala> val people = List(
     |     "Bill", 
     |     "Candy", 
     |     "Karen", 
     |     "Leo", 
     |     "Regina"
     | )
people: List[String] = List(Bill, Candy, Karen, Leo, Regina)

scala> for (p <- people) println(p)
Bill
Candy
Karen
Leo
Regina

foreach方法

foreach方法可以被scala集合类型的类创建的对象访问

scala> people.foreach(println)
Bill
Candy
Karen
Leo
Regina

使用for与foreach访问maps

Map集合 电影名称 及评分,使用上和java的HashMap类似

val ratings = Map(
    "Lady in the Water"  -> 3.0, 
    "Snakes on a Plane"  -> 4.0, 
    "You, Me and Dupree" -> 3.5
)
for((name,rating)<- ratings) println(s"Movie:$name,Rating:$rating")
scala> val ratings = Map(
     |     "Lady in the Water"  -> 3.0, 
     |     "Snakes on a Plane"  -> 4.0, 
     |     "You, Me and Dupree" -> 3.5
     | )
ratings: scala.collection.immutable.Map[String,Double] = Map(Lady in the Water -> 3.0, Snakes on a Plane -> 4.0, You, Me and Dupree -> 3.5)

scala> for((name,rating)<- ratings) println(s"Movie:$name,Rating:$rating")
Movie:Lady in the Water,Rating:3.0
Movie:Snakes on a Plane,Rating:4.0
Movie:You, Me and Dupree,Rating:3.5
ratings.foreach{
	case(movie,rating) => println(s"key:$movie,value:$rating")
}
scala> ratings.foreach{
     |   case(movie,rating) => println(s"key:$movie,value:$rating")
     | }
key:Lady in the Water,value:3.0
key:Snakes on a Plane,value:4.0
key:You, Me and Dupree,value:3.5

for表达式

在scala语言中,除了for循环外,还有更强大的for表达式,for表达用于从现有集合中创建新的集合

代码
scala> val nums = Seq(1,2,3)
nums: Seq[Int] = List(1, 2, 3)
// for(n <- nums) yield n*2 表达式的意思是 nums中的每个n值都翻倍,然后赋值给doubledNums形成新的集合
scala> val doubledNums=for(n <- nums) yield n*2
doubledNums: Seq[Int] = List(2, 4, 6)

将小写字符串集合全大写

scala> val names = List("adam", "david", "frank")
names: List[String] = List(adam, david, frank)

scala> val ucNames = for(name <- names) yield name.capitalize
ucNames: List[String] = List(Adam, David, Frank)

注意: 所有的for表达式使用 yield 关键字

val doubledNums = for (n <- nums) yield n * 2
                                  -----
val ucNames = for (name <- names) yield name.capitalize
                                  -----

yield后使用代码块

scala> val names = List("_adam", "_david", "_frank")
names: List[String] = List(_adam, _david, _frank)

scala> val capNames = for (name <- names) yield {
     |     val nameWithoutUnderscore = name.drop(1)
     |     val capName = nameWithoutUnderscore.capitalize
     |     capName
     | }
capNames: List[String] = List(Adam, David, Frank)

简写

scala> val capNames = for (name <- names) yield name.drop(1).capitalize
capNames: List[String] = List(Adam, David, Frank)

scala> val capNames = for (name <- names) yield { name.drop(1).capitalize }
capNames: List[String] = List(Adam, David, Frank)

match表达式

scala有match表达式概念,最简单的情况下,类似java switch语句匹配表达式

代码
// i is an integer
i match {
    case 1  => println("January")
    case 2  => println("February")
    case 3  => println("March")
    case 4  => println("April")
    case 5  => println("May")
    case 6  => println("June")
    case 7  => println("July")
    case 8  => println("August")
    case 9  => println("September")
    case 10 => println("October")
    case 11 => println("November")
    case 12 => println("December")
    // catch the default with a variable so you can print it
    case _  => println("Invalid month")
}
# i 改为则直接出结果
scala> val monthName = 2 match {
     |     case 1  => "January"
     |     case 2  => "February"
     |     case 3  => "March"
     |     case 4  => "April"
     |     case 5  => "May"
     |     case 6  => "June"
     |     case 7  => "July"
     |     case 8  => "August"
     |     case 9  => "September"
     |     case 10 => "October"
     |     case 11 => "November"
     |     case 12 => "December"
     |     case _  => "Invalid month"
     | }
monthName: String = February

scala method

此节 方法 不是重点,简单了解

def convertBooleanToStringMessage(bool: Boolean): String = {
    if (bool) "true" else "false"        
}
scala> def convertBooleanToStringMessage(bool: Boolean): String = {
     |     if (bool) "true" else "false"        
     | }
convertBooleanToStringMessage: (bool: Boolean)String

scala> val answer = convertBooleanToStringMessage(true)
answer: String = true

scala> val answer = convertBooleanToStringMessage(false)
answer: String = false

使用匹配表达式作为方法的主体

def convertBooleanToStringMessage(bool:Boolean):String = bool match{
	case true => "you said true"
	case false => "you said false"
}

上述方法中,方法体中仅有两行语句,一个匹配 true ,另一个匹配 false ,不需要 default case 语句

scala> def convertBooleanToStringMessage(bool: Boolean): String = bool match {
     |     case true => "you said true"
     |     case false => "you said false"
     | }
convertBooleanToStringMessage: (bool: Boolean)String

scala> val result = convertBooleanToStringMessage(true)
result: String = you said true

scala> println(result)
you said true

其它案例

match 表达式是非常强大的,在此将展示一下其它的案例
match 表达式允许一个 case 处理多个 cases ,下面将演示案例

// 例子一
def isTrue(a:Any) = a match {
	case 0 | "" => false
	case _ => true
}
// 例子二
val evenOrOdd = i match {
    case 1 | 3 | 5 | 7 | 9 => println("odd")
    case 2 | 4 | 6 | 8 | 10 => println("even")
    case _ => println("some other number")
}

在case语句中使用if表达式

在case语句中使用if表达式,可以增加 case 的灵活性

// 最简写的例子
count match {
    case 1 => 
        println("one, a lonely number")
    case x if x == 2 || x == 3 => 
        println("two's company, three's a crowd")
    case x if x > 3 => 
        println("4+, that's a party")
    case _ => 
        println("i'm guessing your number is zero or less")
}

上述案例命令行执行测试

scala> 2 match {
     |     case 1 => 
     |         println("one, a lonely number")
     |     case x if x == 2 || x == 3 => 
     |         println("two's company, three's a crowd")
     |     case x if x > 3 => 
     |         println("4+, that's a party")
     |     case _ => 
     |         println("i'm guessing your number is zero or less")
     | }
two's company, three's a crowd

匹配数字范围示例

i match {
  case a if 0 to 9 contains a => println("0-9 range: " + a)
  case b if 10 to 19 contains b => println("10-19 range: " + b)
  case c if 20 to 29 contains c => println("20-29 range: " + c)
  case _ => println("Hmmm...")
}

在if表达式中如何引用类中的字段

stock match {
  case x if (x.symbol == "XYZ" && x.price < 20) => buy(x)
  case x if (x.symbol == "XYZ" && x.price > 50) => sell(x)
  case x => doNothing(x)
}

try/catch/finally 表达式

与Java一样,scala也有一个try/catch/finaly构造,可以让捕获和管理异常。主要区别在于,为了保持一致性,scala使用了与匹配表达式相同的语法:case语句来匹配可能发生的不同异常。

代码

try/catch

var text = ""
try {
    text = openAndReadAFile(filename)
} catch {
    case e: FileNotFoundException => println("Couldn't find that file.")
    case e: IOException => println("Had an IOException trying to read that file")
}

try, catch, and finally

try {
    // your scala code here
} 
catch {
    case foo: FooException => handleFooException(foo)
    case bar: BarException => handleBarException(bar)
    case _: Throwable => println("Got some other kind of Throwable exception")
} finally {
    // your scala code here, such as closing a database connection
    // or file handle
}

后续

后续的文章中,会接着说明,如函数异常处理

结束

scala控制结构这一块就结束了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

流月up

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值