Scala声明变量、常用类型、条件表达式、块表达式、循环
一、 Scala基础
1. 声明变量
package cn.toto.scala/*** Created by toto on 2017/6/27.*/
object VariableDemo {def main(args: Array[String]): Unit = {//使用val定义的变量值是不可变的,相当于java里用final修饰的变量,不可以再改变参数的值val i = 1println("参数i的值是:" + i)//使用var定义的变量是可变的,在scala中鼓励使用valvar s = "hello";println("参数s的值是:" + s)//修改一下s的值s = "hello word";println("修改后的参数s的值是:" + s)//Scala编译器会自动推断变量的类型,必要的时候可以指定类型//变量名在前,类型在后val str : String = "toto";println("带有参数类型说明的变量str的值是:" + str);}
}
运行结果:
参数i的值是:1
参数s的值是:hello
修改后的参数s的值是:hello word
带有参数类型说明的变量str的值是:toto
2. 常用类型
Scala和Java一样,有7种数值类型Byte、Char、Short、Int、Long、Float和Double(无包装类型)和一个Boolean类型
3. 条件表达式
Scala的的条件表达式比较简洁,例如:
package cn.toto.scala/*** Created by toto on 2017/6/27.*/
object ConditionDemo {def main(args: Array[String]): Unit = {val x = 1//判断x的值,将结果赋给yval y = if(x > 0) 1 else -1//打印y的值println(y)//支持混合类型表达式val z = if(x > 1) 1 else "error"//打印z的值println(z)//如果缺失else,相当于if(x > 2) 1 else ()val m = if(x > 2) 1println(m)//在scala中每个表达式都有值,scala中有个Unit类,写做(),相当于Java中的voidval n = if(x > 2) 1 else ()println(n)//If和else ifval k = if(x < 0) {0} else if(x >= 1) {1} else {-1}println(k);}
}
运行结果:
1
error
()
()
1
4. 块表达式
package cn.toto.scala/*** Created by toto on 2017/6/27.*/
object BlockExpressionDemo {def main(args: Array[String]): Unit = {val x = 0//在scala中的{}中可包含一系列表达式,快中最后一个表达式的值就是块的值,下面就是一个块表达式val result = {if(x < 0) {-1} else if(x >= 1) {1} else {"error"}}//result的值就是块表达式的结果println(result)}
}
运行结果:
error
5. 循环
在scala中有for循环和while循环,用for循环比较多
for循环语法结构:for (i <- 表达式/数组/集合)
package cn.toto.scala/*** Created by toto on 2017/6/27.*/
object ForDemo {def main(args: Array[String]): Unit = {//for(i <- 表达式),表达式1 to 10返回一个Range(区间)//每次循环将区间中的一个值赋给ifor(i <- 1 to 10) {print(i + " ")}println("")//for(i <- 数组)val arr = Array("a","b","c")for(i <- arr) {print(i + " ");}println("")//高级for循环//每个生成器都可以带一个条件,注意:if前面没有分号for(i <- 1 to 3; j <- 1 to 3 if i != j) {print((10 * i + j) + " ")}println()//for推导式:如果for循环的循环体以yield开始,则该循环会构建出一个集合//每次迭代生成集合中的一个值val v = for(i <- 1 to 10) yield i * 10println(v)}
}
运行结果:
1 2 3 4 5 6 7 8 9 10
a b c
12 13 21 23 31 32
Vector(10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
