Scala
--------------
Java语言脚本化
面向函数:直奔主题
直接写程序,直接运行即可。
进入Scala shell
-----------------
$>bin/scala
$scala>:help //查看帮助
o.getClass();
classOf(res6)
inter::类型推断
Int -->RichInt
Double -->RichDouble
Char -->RichChar
scala java
-----------------------------
Int int+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.打印
print("hello")
println("hello")
5.可以使用readLine从控制台读取一行输入
readLine("xxx") //字符串
readLine("age") //Int
6.循环:与c++,java一样的while循环
[while]
var i = 0;
while(i<10){
| i=i+1;
| println(i)
}
[for]
for(i <- 1 to 10){
| print(i)
|}
for(i <- 1 until 10){println(i)}
Map + reduce
----------------------
map() :
scala break操作
Scala没有提供break和continue语句来退出循环
可以用breakable块
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循环,打印正三角形9*9表格
----------------------------------
for(i <- 1 to 9;j <- 1 to 9){
if(i >= j) print(i + "x" + j + "=" + (i + j) + " ")
if(j==i) println()
}
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 abs(x:Double) = if (x >= 0) x else -x
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 5) //error,类型不匹配
$scala>var x = sum(1 to 5:_*) 加上":_*"转换成参数序列。
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
$scala>val x = new Array[Int](10) //0.0.0.0.....
$scala>val x = new Array[String](10)null,null,null,....
$scala>var x = Array("hello" + "world")
$scala>x(3) //方法数组元素
ArrayBuffer //数组缓冲区
$scala> scala.collection.mutable.ArrayBuffer
scala>var x = ArrayBuffer[Int]()
scala>x ++= Array(1,2,3) //使用++=操纵任何集合
scala>x.trimEnd(5) //移除最右的n个元素
scala>x.insert(2,3,4,5,6) //在2位置插入3.。。
scala>x.remove(2,3) //从2开始移除,移除3个
scala>x.remove(2) //x.remove(2,1)
scala>buffer.toArray //从buffer到Array之间的转换
scala>array.toBuffer //..
scala>for(i <- buffer | array) .. //遍历buffer|array
//yield遍历过程中,生成新的集合
scala>for(i <- 1 to 5 if i % 2 == 0) yield i * 2 //先filter,再乘以2产生新集合
scala>var x = Array(1 to 5)
//内置函数
scala>Array(1,2,3).sum
//缓冲区排序
scala>y.sorted(_<_) //升序排序
//快速排序
Scala>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的互操作
-------------------------------
。。。。。
map tuple(映像和元组)
-----------------------
1.java.util.Map
java.util.HashMap
java.util.TreeMap
2.var map = Map("001"->"tom","002"->"tomas","003"->"tomasLee")
3.var map = collection.mutable.Map("001"->"tom","002"->"tomas","003"->"tomasLee")
4.map("001") //get
map.contais("001") //判断是否存在
map.getOrElse("001","nobody") //组合
map("001") = "xxx" //赋值
5.map2 - "004" //支持
迭代
---------
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]
tuple(元组)
-----------------------
元组,Map是有两个元素的元组
元组最多支持22元素
TupleX
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 value = 0
def addOne() = {age += 1}
def compare(b:Dog) = {age < b.age}
}
class Counter{
privte var value = 0
def increment() = value += 1
def current() = value
}
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 //赋值
如果主构造函数的参数使用了var或val,他们会生成对应的字段。如果没有使用的话,但在方法中进行了访问,自动升级成字段。
7.java构造函数的第一条构造语句
class Dog{
public Dog(){
this.
}
}
8.嵌套类(内部类)
class Car{
class Engine{
}
}
对象Object
---------------------
1.定义单例对象
[Box.scala]
object Box{
def getColor = "yellow"
}
[Box.class]
fine class Box{
public static String getColor();
}
class Counter{
private var value = 0;
def increment() = value += 1
def current() = value
}