1 常量、变量、数据类型
常量:
val 名称:数据类型=xxx
变量:
var 名称:数据类型=xxx
数据类型可以省略:
scala> val a=1
a: Int = 1
scala> var b=2
b: Int = 2
scala> b=3
b: Int = 3
scala> a=4
<console>:12: error: reassignment to val
a=4
^
2 基本数据类型
Byte/Char
Short/Int/Long/Float/Double
Boolean
// float需要在数字后面加f
scala> val e=1.1f
e: Float = 1.1
scala> val ee=1.0
ee: Double = 1.0
类型转换
scala> 10.asInstanceOf[Double]
res0: Double = 10.0
判断类型
scala> 10.isInstanceOf[Int]
res1: Boolean = true
3 lazy
使用lazy时,定义变量或常量不会立即返回结果,使用的时候才会返回结果。
scala> lazy val aa=1
aa: Int = <lazy>
scala> aa+b
res2: Int = 4
4 方法的定义与使用
def 方法名(参数名:参数类型):返回值类型={
方法体
// 不需要return
}
scala> def max(x:Int,y:Int): Int ={
| if(x>y) {
| x
| }else{
| y
| }
| }
max: (x: Int, y: Int)Int
scala> max(4,5)
res5: Int = 5
// 方法简写
scala> def four()=1+3
four: ()Int
// 方法调用时可以不加括号
scala> four
res6: Int = 4
1)默认参数:在函数定义时,默认函数参数的缺省值
scala> def sayHello(name:String="lihaogn"): Unit ={
| println("hello"+name)
| }
sayHello: (name: String)Unit
// 有默认参数时要加上括号,否则报错
scala> sayHello
<console>:13: error: missing argument list for method sayHello
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `sayHello _` or `sayHello(_)` instead of `sayHello`.
sayHello
^
scala> sayHello()
hellolihaogn
// 不使用默认参数
scala> sayHello("lisi")
hellolisi
2)命名参数
scala> def userInfo(user:String,pwd:String): Unit ={
| print(user+" "+pwd)
| }
userInfo: (user: String, pwd: String)Unit
// 调用方法时可以不按照顺序写参数,但要写参数名
scala> userInfo(pwd="12345",user="lihaogn")
lihaogn 12345
3)可变参数
scala> def sum(numbers: Int*): Int = {
| var result = 0
| for (number <- numbers) {
| result += number
| }
| result
| }
sum: (numbers: Int*)Int
scala> sum(1,2,3,4,5)
res12: Int = 15
5 条件表达式
scala> if(a>9) print("yes") else print("no")
no
6 循环表达式
scala> 1 to 10
res15: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
scala> 1 until 10
res16: scala.collection.immutable.Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9)
scala> Range(1,10)
res17: scala.collection.immutable.Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9)
scala> Range(1,10,2)
res18: scala.collection.immutable.Range = Range(1, 3, 5, 7, 9)
scala> Range(10,1,-1)
res19: scala.collection.immutable.Range = Range(10, 9, 8, 7, 6, 5, 4, 3, 2)
1)for循环
scala> for (i <- 1 to 10) {
| print(i + " ")
| }
1 2 3 4 5 6 7 8 9 10
scala> for (i <- 1 to 10 if i % 2 == 0) {
| print(i + " ")
| }
2 4 6 8 10
scala> val names = Array("lisi", "zhangsan", "wanger")
names: Array[String] = Array(lisi, zhangsan, wanger)
scala> for (name <- names) {
| println(name)
| }
lisi
zhangsan
wanger
scala> names.foreach(name => println(name))
lisi
zhangsan
wanger
2)while循环
scala> var (sum,n)=(0,1)
sum: Int = 0
n: Int = 1
scala> while(n<=10){
| sum+=n
| n+=1
| }
scala> print(sum)
55