val 不可变 var可变
val myStr=“hello world!”
val myStr1:String=“hello world!”
val myStr2:java.lang.String=“hello world!”
import java.lang._ //java lang包里所有东西
Scala数据类型(都是类,scala.Int)
特殊:String java.lang.String
Byte Char Short Int Long Float Double Boolean
操作符
a 方法 b 等价于 a.方法(b)
例如:val sum1=5+3 val sum2=(5).+(3)
没有++ – 只能 a+=1
富包装类
scala.Int 有基本的计算方法,如+ - * /
某些方法不是基本的计算方法,如求两个数较大的那个,这些方法就在富包装类中实现
3 max 5 ===》 5
Range(for循环经常用到)可以支持不同数据类型的数值序列(Int Long Float Double Char BigInt BigDecimal)
例如:
1 to 5等价于1.to(5) (1,2,3,4,5)
1 until 5 (1,2,3,4)
1 to 10 by 2 (1,3,5,7,9)
0.5f to 5.9f by 0.8f (0.5,1.3,2.1,----)
控制台输入输出(import io.StdIn.)
readInt readDouble readByte readShort readFloat readLong readChar readBoolean readLine
默认导入scala.Predef.
print()
println()
printf()支持c语言中的占位符%s
文件
写文件java.io.PrintWriter
val out=new PrintWriter(“output.txt”)
for (i<-1 to 5) out.println(i)
out.close()
读文件scala.io.Source
val inputFile=Source.fromFile(“output.txt”) //返回迭代器
val lines=inputFile.getLines
for (line <- lines) println(line)
异常处理Scala不支持java中的“受检查异常”(checked expection),将所有异常都当作“不受检查异常”(或成为运行时异常)
try{
val file=new FileReader(“input.txt”)
}catch{
case ex:FileNotFoundExpection=>
//process
case ex:IOException=>
//process
}finally{
file.close()
}
控制结构
if
while
for(变量<- 表达式) “变量<- 表达式”被称为生成器
for(i<-1 to 5) println(i)
守卫表达式
for(i<-1 to 5 if i%20) println(i)
多个生成器(双重循环)
for(i<- 1to 5;j <- 1 to 3) println(i*j)
多个生成器,每个生成器加守卫
for(i<- 1to 5 if i%20;j <- 1 to 3 if j!