scala語言基礎
阿新 • • 發佈:2018-12-25
scala
-------------
java語言指令碼化。
面向函式:直奔主題
直接寫程式,直接執行即可。
java
-------------
javac java
*.java --------> *.class ------> App
scalac scala
*.scala -------> *.class -------> App
安裝scala
----------------
1.準備jdk
略
2.安裝scala
a.
b.
c.
d.
scala vs java
-------------------
進入scala shell
---------------
$>bin/scala
$scala>:help //檢視幫助
o.getClass();
classOf(res6)
infer:;型別推斷.
Int--> RichInt
Double--> RichDouble
Char--> RichChar
Long l = 100 ;//隱式轉換
Short s = (Short)xxx//強轉,顯式轉換
scala|java
-------------------------------------------
Intint + Integer
val(value)final:常量
var可以修改(變數)
var x : String = "hello"
Any(任意)Object
1.toString()//自動1 ->Integer
1.to(10)//方法
1 to 10//操作符
使用函式進行資料型別轉換
var a:Int = 100 ;
var b:Short = 100 ;
b = (Short)a//error
b = a.toShort//ok
++ / --//error,不支援
+=| -= //ok
函式 | 方法
---------------
函式:不需要通過類即可直接呼叫的方法。min power
import scala.math._//_ === *
sqrt(2)//開發
pow(n)//幾次方
單例物件
----------------
class Xxxx{
..
}
object Xxxx{
}
REPL : read + eval + print + loop
無參的函式使用時可以省略()
--------------------------
$scala>1.toString()
$scala>1.toString
apply
--------------------------
1.$scala>"hello"(4)//String.chatAt(i)
2.$scala>"hello".apply(4)//String.chatAt(i)
3.$scala>BigInt("1234")//BigInt.apply("1234567")
控制結構 + 函式
------------------------
1.條件表示式(if else)有值
2.三元運算子
...
val y = if (x > 0) 1
val y = if (x > 0) 1 else ()//() == 不存在 Unit === void
3.進入shell的貼上模式
$scala>:paste
$scala> //CTRL +D
4.列印
println("hello")
print("hello")
5.從命令列輸入讀取資料
readLine("xxx")//字串
readInt("age")//Int
6.迴圈
[while]
var i = 0 ;
while(i < 10){
i += 1
println(i)
}
[for]
for(i <- 1 to 10){
println(i)
}
for(i <- 1 until 10){println(i)}
1 to 10//1,..,10
1 until 10//1,..,9
Map + reduce
--------------
map() :
scala break操作,注意tab問題
------------------------------
import scala.util.control.Breaks._
breakable{
for(i <- 1 to 10){
if(i < 5) println(i) else break ;
}
}
[a.scala]
$scala>load /home/ubuntu/a.scala
高階for迴圈,列印正三角9x9表格
-------------------------------
for(i <- 1 to 9 ; j <- 1 to 9 ){
if(i >= j) print(i + " x " + j + " = " + (i * j) + " ")
if(j == i) println()
}
for推導式: yield,迴圈期間,每次
產生新值放入集合中。將迴圈匯出成向量。
-------------------------------
放棄,產生.
var x = for(i <- 1 to 10) yield i % 3
x: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 0, 1, 2, 0, 1, 2, 0, 1)
函式,遞迴函式必須宣告返回型別。
---------------
[定義]
def fname(pname:ptype,) : retype = body
def add(a:Int,b:Int) : Int = a + b
[階乘函式(迴圈方式)]
def fac(n:Int) = {
var r = 1 ;
for(i <- 1 to n) r = r * i
r
}
[階乘函式(遞迴方式)]
def fac(n:Int) : Int = {
if(n == 1) 1 else fac(n-1)*n
}
fac(6) = 6 * fac(5) ==> 6 * 5 * fac(4) ==> .... =>
apply
----------------
"xxx"(4) //"xxx".apply(4)
預設引數值,帶名引數
--------------------
public String xxx(String a,String b = "xxx"){
...
}
$scala>def dec(a:String,left:String = "[",right:String="]") : String = left + a + right
$scala>var x = dec("tom")//x = [tom]//預設值
$scala>var x = dec(a="tom",right="###")//x = [tom]//指名引數
變長引數
-------------------
def sum(args:Int*) = {
var x = 0 ;
for(i <- args) r = r + i
r
}
$scala>var x = sum(1,2,3,4,5);
$scala>var x = sum(1 to 8)//error,型別不匹配
$scala>var x = sum(1 to 8: _*)//error,型別不匹配,將range轉變成引數序列。
1 to n //Range區間,不是Seq。
def rsum(args:Int*):Int = {
if(args.length == 0) 0
else args.head + rsum(args.tail:_*)
}
instanceof //
getClass() == Xxx.class//
過程,不返回值的函式,不使用 = 附作用.
----------------------
def box(name:String){
println("$$$" + name + "$$$")
}
def box(name:String): Unit = {
println("$$$" + name + "$$$")
}
lazy value:延遲求值
--------------------
$scala>lazy val x = scala.io.source.FromFile("/xx/x/x/").mkString//延遲求值
$scala>x
異常
--------------------
java : Throwable Error() + Exception(RuntimeException)
public void add(..) {
try{
_
}
catch(X1Exception e1){
e1
}
catch(X2Exception e2){
}
}
checked //待檢
managed //託管
try{
...
}
catch{
case _ : XxxxException => xxx//進入xxx處理程式
case ex : XxxxException => ex.printStackTrace()//進入xxx處理程式
//越具體的異常越靠前
}
陣列 + 緩衝區
-------------------
int[]
ByteBuffer
Array//定長
ArrayBuffer //變長
$scala>var x = new Array[Int](10)//0,0,0,0,0,..
$scala>var x = new Array[String](10)//null,null,..
$scala>var x = Array("hello","world")//
$scala>x(3) //方法陣列元素
ArrayBuffer //陣列緩衝區
$scala>scala.collection.mutable.ArrayBuffer
$>var x = ArrayBuffer[Int]()
$>x ++= Array(1,2,3)//使用++=操縱任何集合
$>x.trimEnd(5)//移除最有的n個元素
$>x.insert(2,3,4,5,6)//在2位置插入3...
$>x.remove(2,3)//從2開始移除,移除3個
$>x.remove(2) //x.remove(2,1)
$>buffer.toArray//從buffer到Array之間轉換
$>array.toBuffer//..
$scala>for(i <- buffer | array) ..//遍歷buffer|array
//yield遍歷過程中,生成新的集合
$scala>for(i <- 1 to 5 if i % 2 == 0) yield i * 2 ;//先filter , 再 x 2產生新集合
$scala>var x = Array(1 to 5)
//內建函式
$scala>Array(1,2,3).sum
//緩衝區排序
$scala>y.sorted(_ < _)//????????????升序排序??????????????
//快速排序
$>var x = Array(1,7,2,9)
$scala>scala.util.Sorting.quickSort(a)//
//mkString
$scala>a.mkString(" and ")
多維陣列
--------------
int[層][行][列] cube ;//java
Array[Array[Array[Int]]]//scala
$scala>var x = Array.ofDim[Int](3,3,3)//三維陣列
$scala>var idx = 1 ;
for(i <- 0 until x.length){
for(j <- 0 until x(i).length){
for(k <- 0 until x(i)(j).length){
x(i)(j)(k) = idx ;
idx += 1
}
}
}
//使用不等長元素的多維陣列
$scala>var x = new Array[Array[Int]](4)
java和scala的互操作
------------------------
ProcessBuilder builder = new ProcessBuilder();
List<String> list = new ArrayList<String>();
list.add("dir");
list.add("d:\\downloads");
Process p = builder.command(list).start();
InputStream is = p.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = 0 ;
byte[] buf = new byte[1024];
while((len = is.read(buf)) != -1){
baos.write(buf, 0, len);
}
is.close();
System.out.println(new String(baos.toByteArray()));
1.import scala.collection.JavaConversions.bufferAsJavaList
2.var cmd = ArrayBuffer("ls","-al","/home/ubuntu")
3.var pb = new ProcessBuilder(cmd);//自動轉換
$scala>import scala.collection.JavaConversions.asScalaBuffer
$scala>import scala.collection.mutable.Buffer
$scala>var rr:Buffer[String] = pb.command
map + tuple
-------------------
1.java.util.Map
java.util.HashMap
java.util.TreeMap
2.var map = Map("001"->"tom","002"->"tomas","003"->"tomasLee")//scala 不可變
2.var map2 = Map(("001","tom"),("002","tomas"),("003","tomasLee"))//scala 不可變
3.var map = collection.mutable.Map("001"->"tom","002"->"tomas","003"->"tomasLee")//可變
4.map("001") //get
4.map.contais("001")//判斷是否存在
4.map.getOrElse("001","nobody")//組合
4.map("001") = "xxx"//賦值
5.map2 - "004"//支援-
//迭代
5.scala>for((k,v) <- map) println(k + "-----" + v)//遍歷
//java
map.keySet() //key集合
map.values() //value集合
//排序map
$scala>import scala.collection.immutable.SortedMap
//實現java和scala之間map的相互轉換
$scala>var m : scala.collection.mutable.Map[String,String] = new java.util.TreeMap[String,String]
tuple
-----------------------
元組,Map是有兩個元素的元組。
元組最多支援22元素
TupleX //tab可見
$scala>var t : Tuple3[Int,String,Int] = (1,"tom",12)//tuple
$scala>t._1 //n從1開始
$scala>val (id,name,age) = t
$scala>id
$scala>name
$scala>age
zip:咬合操作
-----------------------
兩個陣列的元素一一組合。
$scala>var ids = Array("001","002","003")
$scala>var names = Array("tom","tomas","tomasLee")
$scala>var pairs = ids.zip(names)
類
-------------
1.class Classname{
private var id = 0 ;//必須初始化,否則需要宣告成abstract
}
2.class Counter{
private var value = 0 ;
def increment() = value += 1
def current() = value
}
3.getter和setter
getter //age
setter //age=
4.Dog//可以更加豐富的控制可見性
class Dog{
private[this] var age = 0
def addOne() = {age +=1}
def compare(b:Dog)={age < b.age}
}
5.scala.beans.BeanProperty
class Dog{
@BeanProperty private var age = 0//生成getter / setter
def addOne() = {age +=1}
def compare(b:Dog)={age < b.age}
}
6.輔助建構函式
class Dog{
...
def this(name:String){
this() //主構造
this.name = name ;//賦值
}
def this(name:String,age:Int){
this(name)
this.age = age ;
}
}
如果主建構函式的引數使用了var或val,他們會生成對應的欄位。
如果沒有使用的話,但在方法中進行了訪問,自動升級成欄位。
7.java建構函式的第一條語句
class Dog{
public Dog(){
this(..) / super(...)
}
}
8.巢狀類(內部類)
class Car{
class Engine{
}
}
9.伴生物件
class + object(和class同名)
10.scala應用程式
a.編寫scala檔案
object Hello{
def main(args:Array[String]){
println("hello world")
}
}
b.編譯scala檔案
$>scalac hello.scala
c.執行
$>scala Hello
package / import
-------------------------
1.
2.
3.
4.
5.
6.
物件:object
--------------------
1.定義單例物件
[Box.scala]
object Box{
def getColor = "yellow"
}
[Box.class]
find class Box{
public static String getColor();
}
2.
3.
class Counter{
private var value = 0 ;
def increment() = value += 1
def current() = value
}
-------------
java語言指令碼化。
面向函式:直奔主題
直接寫程式,直接執行即可。
java
-------------
javac java
*.java --------> *.class ------> App
scalac scala
*.scala -------> *.class -------> App
安裝scala
----------------
1.準備jdk
略
2.安裝scala
a.
b.
c.
d.
scala vs java
-------------------
進入scala shell
---------------
$>bin/scala
$scala>:help //檢視幫助
o.getClass();
classOf(res6)
infer:;型別推斷.
Int--> RichInt
Double--> RichDouble
Char--> RichChar
Long l = 100 ;//隱式轉換
Short s = (Short)xxx//強轉,顯式轉換
scala|java
-------------------------------------------
Intint + Integer
val(value)final:常量
var可以修改(變數)
var x : String = "hello"
Any(任意)Object
1.toString()//自動1 ->Integer
1.to(10)//方法
1 to 10//操作符
使用函式進行資料型別轉換
var a:Int = 100 ;
var b:Short = 100 ;
b = (Short)a//error
b = a.toShort//ok
++ / --//error,不支援
+=| -= //ok
函式 | 方法
---------------
函式:不需要通過類即可直接呼叫的方法。min power
import scala.math._//_ === *
sqrt(2)//開發
pow(n)//幾次方
單例物件
----------------
class Xxxx{
..
}
object Xxxx{
}
REPL : read + eval + print + loop
無參的函式使用時可以省略()
--------------------------
$scala>1.toString()
$scala>1.toString
apply
--------------------------
1.$scala>"hello"(4)//String.chatAt(i)
2.$scala>"hello".apply(4)//String.chatAt(i)
3.$scala>BigInt("1234")//BigInt.apply("1234567")
控制結構 + 函式
------------------------
1.條件表示式(if else)有值
2.三元運算子
...
val y = if (x > 0) 1
val y = if (x > 0) 1 else ()//() == 不存在 Unit === void
3.進入shell的貼上模式
$scala>:paste
$scala> //CTRL +D
4.列印
println("hello")
print("hello")
5.從命令列輸入讀取資料
readLine("xxx")//字串
readInt("age")//Int
6.迴圈
[while]
var i = 0 ;
while(i < 10){
i += 1
println(i)
}
[for]
for(i <- 1 to 10){
println(i)
}
for(i <- 1 until 10){println(i)}
1 to 10//1,..,10
1 until 10//1,..,9
Map + reduce
--------------
map() :
scala break操作,注意tab問題
------------------------------
import scala.util.control.Breaks._
breakable{
for(i <- 1 to 10){
if(i < 5) println(i) else break ;
}
}
[a.scala]
$scala>load /home/ubuntu/a.scala
高階for迴圈,列印正三角9x9表格
-------------------------------
for(i <- 1 to 9 ; j <- 1 to 9 ){
if(i >= j) print(i + " x " + j + " = " + (i * j) + " ")
if(j == i) println()
}
for推導式: yield,迴圈期間,每次
產生新值放入集合中。將迴圈匯出成向量。
-------------------------------
放棄,產生.
var x = for(i <- 1 to 10) yield i % 3
x: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 0, 1, 2, 0, 1, 2, 0, 1)
函式,遞迴函式必須宣告返回型別。
---------------
[定義]
def fname(pname:ptype,) : retype = body
def add(a:Int,b:Int) : Int = a + b
[階乘函式(迴圈方式)]
def fac(n:Int) = {
var r = 1 ;
for(i <- 1 to n) r = r * i
r
}
[階乘函式(遞迴方式)]
def fac(n:Int) : Int = {
if(n == 1) 1 else fac(n-1)*n
}
fac(6) = 6 * fac(5) ==> 6 * 5 * fac(4) ==> .... =>
apply
----------------
"xxx"(4) //"xxx".apply(4)
預設引數值,帶名引數
--------------------
public String xxx(String a,String b = "xxx"){
...
}
$scala>def dec(a:String,left:String = "[",right:String="]") : String = left + a + right
$scala>var x = dec("tom")//x = [tom]//預設值
$scala>var x = dec(a="tom",right="###")//x = [tom]//指名引數
變長引數
-------------------
def sum(args:Int*) = {
var x = 0 ;
for(i <- args) r = r + i
r
}
$scala>var x = sum(1,2,3,4,5);
$scala>var x = sum(1 to 8)//error,型別不匹配
$scala>var x = sum(1 to 8: _*)//error,型別不匹配,將range轉變成引數序列。
1 to n //Range區間,不是Seq。
def rsum(args:Int*):Int = {
if(args.length == 0) 0
else args.head + rsum(args.tail:_*)
}
instanceof //
getClass() == Xxx.class//
過程,不返回值的函式,不使用 = 附作用.
----------------------
def box(name:String){
println("$$$" + name + "$$$")
}
def box(name:String): Unit = {
println("$$$" + name + "$$$")
}
lazy value:延遲求值
--------------------
$scala>lazy val x = scala.io.source.FromFile("/xx/x/x/").mkString//延遲求值
$scala>x
異常
--------------------
java : Throwable Error() + Exception(RuntimeException)
public void add(..) {
try{
_
}
catch(X1Exception e1){
e1
}
catch(X2Exception e2){
}
}
checked //待檢
managed //託管
try{
...
}
catch{
case _ : XxxxException => xxx//進入xxx處理程式
case ex : XxxxException => ex.printStackTrace()//進入xxx處理程式
//越具體的異常越靠前
}
陣列 + 緩衝區
-------------------
int[]
ByteBuffer
Array//定長
ArrayBuffer //變長
$scala>var x = new Array[Int](10)//0,0,0,0,0,..
$scala>var x = new Array[String](10)//null,null,..
$scala>var x = Array("hello","world")//
$scala>x(3) //方法陣列元素
ArrayBuffer //陣列緩衝區
$scala>scala.collection.mutable.ArrayBuffer
$>var x = ArrayBuffer[Int]()
$>x ++= Array(1,2,3)//使用++=操縱任何集合
$>x.trimEnd(5)//移除最有的n個元素
$>x.insert(2,3,4,5,6)//在2位置插入3...
$>x.remove(2,3)//從2開始移除,移除3個
$>x.remove(2) //x.remove(2,1)
$>buffer.toArray//從buffer到Array之間轉換
$>array.toBuffer//..
$scala>for(i <- buffer | array) ..//遍歷buffer|array
//yield遍歷過程中,生成新的集合
$scala>for(i <- 1 to 5 if i % 2 == 0) yield i * 2 ;//先filter , 再 x 2產生新集合
$scala>var x = Array(1 to 5)
//內建函式
$scala>Array(1,2,3).sum
//緩衝區排序
$scala>y.sorted(_ < _)//????????????升序排序??????????????
//快速排序
$>var x = Array(1,7,2,9)
$scala>scala.util.Sorting.quickSort(a)//
//mkString
$scala>a.mkString(" and ")
多維陣列
--------------
int[層][行][列] cube ;//java
Array[Array[Array[Int]]]//scala
$scala>var x = Array.ofDim[Int](3,3,3)//三維陣列
$scala>var idx = 1 ;
for(i <- 0 until x.length){
for(j <- 0 until x(i).length){
for(k <- 0 until x(i)(j).length){
x(i)(j)(k) = idx ;
idx += 1
}
}
}
//使用不等長元素的多維陣列
$scala>var x = new Array[Array[Int]](4)
java和scala的互操作
------------------------
ProcessBuilder builder = new ProcessBuilder();
List<String> list = new ArrayList<String>();
list.add("dir");
list.add("d:\\downloads");
Process p = builder.command(list).start();
InputStream is = p.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = 0 ;
byte[] buf = new byte[1024];
while((len = is.read(buf)) != -1){
baos.write(buf, 0, len);
}
is.close();
System.out.println(new String(baos.toByteArray()));
1.import scala.collection.JavaConversions.bufferAsJavaList
2.var cmd = ArrayBuffer("ls","-al","/home/ubuntu")
3.var pb = new ProcessBuilder(cmd);//自動轉換
$scala>import scala.collection.JavaConversions.asScalaBuffer
$scala>import scala.collection.mutable.Buffer
$scala>var rr:Buffer[String] = pb.command
map + tuple
-------------------
1.java.util.Map
java.util.HashMap
java.util.TreeMap
2.var map = Map("001"->"tom","002"->"tomas","003"->"tomasLee")//scala 不可變
2.var map2 = Map(("001","tom"),("002","tomas"),("003","tomasLee"))//scala 不可變
3.var map = collection.mutable.Map("001"->"tom","002"->"tomas","003"->"tomasLee")//可變
4.map("001") //get
4.map.contais("001")//判斷是否存在
4.map.getOrElse("001","nobody")//組合
4.map("001") = "xxx"//賦值
5.map2 - "004"//支援-
//迭代
5.scala>for((k,v) <- map) println(k + "-----" + v)//遍歷
//java
map.keySet() //key集合
map.values() //value集合
//排序map
$scala>import scala.collection.immutable.SortedMap
//實現java和scala之間map的相互轉換
$scala>var m : scala.collection.mutable.Map[String,String] = new java.util.TreeMap[String,String]
tuple
-----------------------
元組,Map是有兩個元素的元組。
元組最多支援22元素
TupleX //tab可見
$scala>var t : Tuple3[Int,String,Int] = (1,"tom",12)//tuple
$scala>t._1 //n從1開始
$scala>val (id,name,age) = t
$scala>id
$scala>name
$scala>age
zip:咬合操作
-----------------------
兩個陣列的元素一一組合。
$scala>var ids = Array("001","002","003")
$scala>var names = Array("tom","tomas","tomasLee")
$scala>var pairs = ids.zip(names)
類
-------------
1.class Classname{
private var id = 0 ;//必須初始化,否則需要宣告成abstract
}
2.class Counter{
private var value = 0 ;
def increment() = value += 1
def current() = value
}
3.getter和setter
getter //age
setter //age=
4.Dog//可以更加豐富的控制可見性
class Dog{
private[this] var age = 0
def addOne() = {age +=1}
def compare(b:Dog)={age < b.age}
}
5.scala.beans.BeanProperty
class Dog{
@BeanProperty private var age = 0//生成getter / setter
def addOne() = {age +=1}
def compare(b:Dog)={age < b.age}
}
6.輔助建構函式
class Dog{
...
def this(name:String){
this() //主構造
this.name = name ;//賦值
}
def this(name:String,age:Int){
this(name)
this.age = age ;
}
}
如果主建構函式的引數使用了var或val,他們會生成對應的欄位。
如果沒有使用的話,但在方法中進行了訪問,自動升級成欄位。
7.java建構函式的第一條語句
class Dog{
public Dog(){
this(..) / super(...)
}
}
8.巢狀類(內部類)
class Car{
class Engine{
}
}
9.伴生物件
class + object(和class同名)
10.scala應用程式
a.編寫scala檔案
object Hello{
def main(args:Array[String]){
println("hello world")
}
}
b.編譯scala檔案
$>scalac hello.scala
c.執行
$>scala Hello
package / import
-------------------------
1.
2.
3.
4.
5.
6.
物件:object
--------------------
1.定義單例物件
[Box.scala]
object Box{
def getColor = "yellow"
}
[Box.class]
find class Box{
public static String getColor();
}
2.
3.
class Counter{
private var value = 0 ;
def increment() = value += 1
def current() = value
}