首页 技术 正文
技术 2022年11月16日
0 收藏 728 点赞 2,770 浏览 1588 个字

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,比如下面这个例子

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

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子句返回值

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

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

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,027
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,518
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,365
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,146
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,780
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,857