$ scala -help
Welcome to Scala 2.12.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_111).
Type in expressions for evaluation. Or try :help.
$ scala
scala>1+2 //scala支持自动推断类型
res0:Int= 3
scala>1.5*2
res1:Double= 3.0
scala>3*res1
res2:Double= 9.0
scala>res2.to //scala有自动补全功能,tab键
to toChar toDouble toInt toRadians toString
toByte toDegrees toFloat toLong toShort
scala>res2.toInt
res4:Int= 9
scala>val result = 2 + 10 //val 定义变量不可变
result:Int= 12
scala>re
readBoolean readFloat readShort readf3 remote res2
readByte readInt readf ref require res4
readChar readLine readf1 refArrayOps res0result
readDouble readLong readf2 reflect res1
scala>result = 13 //不可变变量赋值报error
:12:error:reassignment to val
result = 13
scala>var name = "123"
name:String= 123
scala>val age :Int = 0
age:Int= 0
scala>val name: String = "lpfasd" //声明时可限定类型
name:String= lpfasd
scala>val a,b,c=0 //可一行赋多数值
a:Int= 0
b:Int= 0
c:Int= 0
scala>0.to(5) //Range代表的是一段整数的范围
res6:scala.collection.immutable.Range.Inclusive= Range 0 to 5
scala>1.+(1) //数字也有方法
res7:Int= 2
scala>1++ //scala中去除了++,--。用+=,-=来替代
:12:error:value ++ is not a member of Int
1++
^
scala>age +=1
:13:error:value += is not a member of Int
Expression does not convert to assignment because receiver is not assignable.
age +=1
^
scala>import scala.math._ //导入文件
import scala.math._
scala>min(20,4) //比较大小
res10:Int= 4
scala>Array(1,2,3,4) //数组初始化
res11:Array[Int]= Array(1, 2, 3, 4)
scala>var array = Array(1,2,3,4) //自动识别类型
array:Array[Int]= Array(1, 2, 3, 4)
scala>array
res13:Array[Int]= Array(1, 2, 3, 4)
scala>array = Arr
ArrayArrayIndexOutOfBoundsExceptionArrowAssoc
ArrayCharSequenceArrayStoreException
scala>array = Array.apply(1,2,3,4)
array: Array[Int] = [I@71d3dfd5
scala>var array = Array.apply(1,2,3,4)
array:Array[Int]= Array(1, 2, 3, 4)
scala>var element = 100
element:Int= 100
scala>while(element>100){ //while循环
|println(element)
|element -= 2}
scala>while(element>10){
|println(element)
|element -= 2}
100
98
96
94
.....
12
scala>0 to element
res17:scala.collection.immutable.Range.Inclusive= Range 0 to 10
scala>for(i<-0 to element)println(i) //for♻️
0
1
2
3
……
scala>for(i<-0 to element if i%2 == 0)println(i) //带过滤条件的查询
0
2
4
6
8
10
//可变参数
scala>def sum(numbers:Int*) = {var result = 0;for(element<-numbers)result +=element;result}
sum:(numbers: Int*)Int
scala>sum(1,2,3,4,5,6,7,8,9)
res20:Int= 45
//引入io包
scala>import scala.io.Source._
//读取源文件(文件不存在,报异常)因是lazy,即不立即执行,所以异常此时并未发生,调用时抛除
scala>lazy val content = fromFile("/root/asdasdasd")
content:scala.io.BufferedSource=
scala>fromFile("/root/asdasdasd")
java.io.FileNotFoundException: /root/asdasdasd (No such file or directory)
//存在编码问题,应注意解码
scala>fromFile("/Users/name/Desktop/123.txt","utf-8")
java.nio.charset.MalformedInputException: Input length = 1
//本例对应“GBK”
scala>fromFile("/Users/liupengfei/Desktop/123.txt","GBK").mkString
res28:String=
1.开源中国
网址https://git.oschina.net/peiphen/test
Git@OSC账户
账号:
密码:
……