1、注意:在Scala中,任何数据都是对象。
举例:数字 1 ----> 是一个对象,就有方法
scala> 1.toString
res0: String = 1 ----> 定义了新的变量 res0,类型String
2、Scala定义变量的时候,可以不指定变量的类型,Scala会进行类型的自动推导
举例:下面的语句是一样的
var a:Int = 10
var b = 10
如何定义常量? val
val c = 10
3、数据的类型
(1)数值类型:复习
(*)Byte: 8位的有符号 -128~127
(*)Short:16位的有符号 -32768 ~ 32767
(*)Int: 32位的有符号
(*)Long: 64位的有符号
(*)Float:浮点数
(*)Double:双精度
(2)字符串:Char、String
对于字符串,在Scala中可以进行插值操作
val s1 = "hello world"
可以在另一个字符串中,引用s1的值
"My name is Tom and ${s1}"
(3)Unit类型:相当于Java中的void 类型
()代表一个函数:没有参数,也没有返回值
scala> val f = ()
f: Unit = ()
val f = (a:Int)
(4)Nothing类型:一般来说,表示在函数(方法)执行过程中产生了Exception
举例: 定义函数 def
def myfunction = throw new Exception("some exception ....")
myfunction: Nothing
四、Scala的函数
1、内置函数:数学运算
举例:求最大值
max(1,2)
包: import scala.math._
https://www.scala-lang.org/files/archive/api/2.11.8/#package
scala> max(1,2)
res4: Int = 2 ----> 定义了一个新的变量来保存运算的结果
var result:Int = max(1,2)
var result = max(1,2)
2、自定义函数:def
3、Scala的条件表达式 if.. else
//注意:scala中函数的最后一句话,就是函数分返回值
//不写reture
五、循环: for、while、do…while
六、Scala函数的参数:求值策略
1、call by value:对函数的实参求值,并且仅求一次
举例:def test1(x:Int,y:Int):Int = x+x 没有用到y
2、call by name:函数的实参每次在函数体内部被调用的时候,都会进行求值
举例:def test2(x: => Int,y: =>Int):Int = x+x 没有用到y
3、一个复杂点的例子
x是call by value
y是call by name
def test3(x:Int,y: =>Int):Int = 1
再定义一个死循环的函数
def loop():Int = loop
考虑下面的两个调用
test3(1,loop) ---> 正常
test3(loop,1) ---> 死循环
4、函数的参数:默认参数、代名参数、可变参数
七、lazy值:如果一个变量被lazy修饰了,他的初始化会被推迟到第一次使用的时候
举例1
scala> var x = 10
x: Int = 10
scala> lazy val y = x + 10
y: Int = <lazy>
scala> y
res0: Int = 20
举例2:读文件(存在)
读文件(不存在)
scala> val words = scala.io.Source.fromFile("d:\\temp\\a.txt").mkString
words: String = I love Beijing
scala> val words1 = scala.io.Source.fromFile("d:\\temp\\b.txt").mkString
java.io.FileNotFoundException: d:\temp\b.txt (系统找不到指定的文件。)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at scala.io.Source$.fromFile(Source.scala:91)
at scala.io.Source$.fromFile(Source.scala:76)
at scala.io.Source$.fromFile(Source.scala:54)
... 32 elided
scala> lazy val words1 = scala.io.Source.fromFile("d:\\temp\\b.txt").mkString
words1: String = <lazy>
scala> words1
java.io.FileNotFoundException: d:\temp\b.txt (系统找不到指定的文件。)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at scala.io.Source$.fromFile(Source.scala:91)
at scala.io.Source$.fromFile(Source.scala:76)
at scala.io.Source$.fromFile(Source.scala:54)
at .words1$lzycompute(<console>:11)
at .words1(<console>:11)
... 32 elided
scala>