Scala II

来源:互联网 发布:声鉴图用什么软件做 编辑:程序博客网 时间:2024/05/21 08:05

脚本语言

sql , js , shell , python所见即所得.repl        //read -> evalute -> print -> loop               javac            javajava : *.java ------->*.class  ------->app

scala

java语句脚本化。

scala

1.下载2.11.82.安装3.scala

scala>
1 + 1
1.+(1) //$plus

val //值类型,等价于java中常量
var //变量

//常量
val a = 1
a = 2 //wrong

//变量
var a = 1
a = 2 //ok

val a:Int = 1

//定义类型
val a:Int = 1
val a:Int = “abc” //wrong
val a:String = “abc”
val a:java.lang.String = “abc”

//同时初始化多个变量
val a,b = 1000

//
1.to(10)
1 to 10
1 == 1
1.==(1)

//字符串交集
“abc”.intersect(“bcd”);

//scala没有++ –,有+= -=

//java:方法和函数没区别
//scala:函数独立调用,不需要通过对象,方法通过对象调用
pow(3,3)

//java : import java.lang.*
//scala : import java.lang._

//import scala.math._
//幂函数
pow(2,2) //
pow(27,1.toFloat/3) //开立方

//平方根
sqrt(4,2);

//apply()
“hello”(4)
“hello”.apply(4)

//条件表达式
val x = 0 ;
var r = if(x > 1) 1 else -1 //Int
var r = if(x > 1) “1” else -1 //Any
var r = if(x > 1) “1” //else缺失,a:Unit = (),类似于null

//scala没有三元运算符 ? :

//换行问题
val r = if(x > 1) {1
}else -1

//粘贴模式
:paste

ctrl + D

//块的值
val r = {1 ;2;3;4} //4

//打印函数
println(“abc”)

//c风格打印
printf(“a=%d , b = %d , c= %s”, 1,2,”abc”)

//读取输入
var name = readLine(“please input your name: “)
printf(“your name is : %s\r\n” , name) ;

//while
var n = 1
while(n < 9){
println(n)
n += 1
}

for(x <- 1 to 10){
println(x)
}

//99表格
var r = 1 ;
while(r <= 9 ){
var c = 1 ;
while(c <= r){
printf(“%dx%d=%d\t”,c , r , (c * r))
c +=1
}
println()
r += 1
}

//99for循环
for(r <- 1 to 9){
for(c <- 1 to r){
printf(“%dx%d=%d\t”,c , r , (c * r))
}
println()
}

//while for实现百钱买百鸡
//100钱
//100鸡
// 5/公鸡 , 3/母鸡 1/3只小鸡

//to
1 to 10 //1 ~ 10
1 until 10 //1 ~ 9

//scala没有break 和 continue
import scala.util.control.Breaks._
for(x <- 1 to 10){println(x) ; break() ;}
for(x <- 1 to 10){println(x) ; continue ;}

//高级for循环,笛卡尔积
for(x <- 1 to 3 ; y <- 1 to 3){printf(“x=%d,y=%d\r\n”, x,y)}

//守卫条件
for(x <- 1 to 3 if x > 1 ; y <- 1 to 3 if x != y){printf(“x=%d,y=%d\r\n”, x,y)}

//yield,产生,生成,for循环推导式
for(x <- 1 to 4) yield x.toString

//计算阶乘,递归函数需要显式定义返回值类型
def fac(n:Int):Int= {if (n == 1) 1 else n * fac(n- 1);}

//带名参数和默认参数
def decorate(pre:String=”<<<”,str:String , suf:String=”>>>”) = pre + str = suf
decorate(str=”hello”)
decorate(str=”hello”,pre=”{{{“)

//变长参数
def sum(a:Int*) = {var s = 0 ; for(x <- a) s += x ; s}

//定义函数
def add(a:Int,b:Int) = a + b
def add(a:Int,b:Int):Int = a + b

//scala中的_用法
1.导包统配,等价于java中的*
import scala.math._

2.将Range对象转换成序列    1 to 10:_*

val
var

for
while
类型推断 : infer

val a:Int = 1 ;
if() else

1 to 10
1 until 10
1.+(1)

for(x <- ){
}

while(){
}

def add(a:Int = 1,b:Int = 2):Int = a + b
add(a = 10)

Unit = ()

//lazy value : 延迟求值。
lazy val words = scala.io.Source.fromFile(“d:/1.txt”)

//scala编写程序时不需要理会异常,(所有异常都是runtime)

//charAt
“hello”(4)
“hello”.apply(4)

//数组,定长数组
val arr = new ArrayString
arr(0)
arr.apply(0)

//变长数组:数组缓冲区
import scala.collection.mutable.ArrayBuffer
val buf = ArrayBufferInt

//=表示修改自身,没有=,表示原来内容不变。
buf += 1
buf ++= buf
buf ++ buf
buf += (1,2,3,4)
//删除后面的5个元素
buf.trimEnd(5)

//在指定位置插入元素,依次后移
buf.insert(0,100)

//删除指定索引的值
buf.remove(2)
//从哪个开始删除几个元素
buf.remove(2,3)
//转换成Array
buf.toArray()
//遍历缓冲区
for(x <- buf) …
//排序
buf.sort(<)

//数组常用方法
val arr = buf.toArray
arr.sum()
arr.max() //
arr.min() //
arr.mkString(“,”) //1,2,3

//多维数组
val arr = Array.ofDimInt //多维数组
for(x <- arr){
for(y <- x){
print(y.toString() + “\t”)
}
println()
}

//赋值
var arr = Array.ofDimInt
var index = 1 ;
var row = 0 ;
while(row < arr.length){
var col = 0 ;
while(col < arr(row).length){
arr(row)(col) = index
col += 1
index += 1
}
row += 1
}

//和java集合的互操作
import scala.collection.JavaConversions.bufferAsJavaList
def getLength(list:java.util.List[Int]) = println(list.size())
getLength(buf) //将scala Buf隐式转换成了java List

//将java list转换成scala buffer
import scala.collection.JavaConversions.as
val list:java.util.List[Int] = buf
val buf2:scala.collection.mutable.Buffer = list //只能是buffer,不能是ArrayBuffer

//映射,不可变集合
val map = Map(1->”tom”,2->”tomas”);
map(1)
map.apply(1)

//可变集合
val map = scala.collection.mutable.Map(1->”tom”,2->”tomson”)
map(1) = “newvalue”

//显式声明集合类型
val map = scala.collection.mutable.MapInt,String
map.+=((1,”tom”))
for((k,v) <- map){
println(k + “:” + v)
}

//对偶,couple,就是一对kv,是二元的元组。(x,y)
//对偶是特殊tuple,有个两个元素。
val c = 1 -> “tom”
val c = (1,”tom”)
val map = Map((1,”tom”),(2,”tomas”))
val map = Map((1->”tom”),(2->”tomas”))

//元组,是不同类型值集合
//元组的范围从Tuple1 ~ Tuple22
val t = (1, “tom”)
t_1
t_2
val t:Tuple3[Int,String,Int] = (1,”tom”,12)
val t:(Int,String,Int) = (1,”tom”,12)
val t = (1,”tom”,12)

t._3
t _3

//抽取元组值
val (id,name,age) = t
val (id,,) = t
val (id,name,_) = t

val ids = Array(1,2,3);
val ids = ArrayInt
ids(0) =1
ids(1) =2
ids(2) =3

//zip
val ids = Array(1,2,3);
val names = Array(“tom”,”tomas”,”tomasLee”);
ids.zip(names)
ids.zipAll(names,-1,”none”) //-1:默认id,”none” : 默认name,长度不等时使用。
ids.zipWithIndex //和索引构成元组

class Dog
val d = new Dog

class Counter{
private var value = 0 //定义成员变量
def incr(){value += 1} //过程,没有返回值
def curr() = value //方法
}

//使用scala编译类
scalac Dog.scala
//查看类结构
javap -p Counter.class

//从磁盘导入scala文件
:load d:/scala/Person.scala
val p = new Person()
p.name //p.name() 等价于get
p.name = //p.name_=(“”) 等价于set

//
class Person{
val age = 0 ; //没有set
var name = “tom” //get/set
}

//私有字段
class Person{
//控制name字段只能在自己的对象中访问。其他对象无法访问.
private[this] var name = “tom” ;
}

//标准get、set方法
import scala.beans.BeanProperty
class Person{
@BeanProperty var name = “tom”
}
val p = new Person()
p.setName(“”); //标准方法

//_使用方法
1.导包
import scala._
2.转换
1 to 10:_*
3.元组抽取
val (id,_) = t

4.属性默认值
class Person{
var name:String = _
}

//scala构造函数
class Cat{
var name = “tom”
//辅助构造
def this(color:String) = {
this()
println(“1”)
}
//重载辅助构造
def this(color:String,age:Int) = {
this(“color”)
println(“2”)
}
}

//主构造,如果private修饰,所有方法都使用private修饰.
class Cat(var name:String,val age:Int,color:String){
def whatColor() = println(color)
}

Compiled from “Cat.scala”
public class Cat {
private java.lang.String name;
private final int age;
public java.lang.String name();
public void name_$eq(java.lang.String); //setName
public int age();
public Cat(java.lang.String, int, java.lang.String);
}

1.主构造参数解释
a)使用var修饰
对应成员变量,生成读写访问
b)使用val修饰
对应final成员变量,只有get方法
c)没有修饰var | val 修饰
c.1)如果类中没有访问过,不生成成员变量
c.2)如果访问过,生成成员变量。没有方法。final
2.主构造使用默认值
class Dog(name:String = “dahuang” , age:Int = 2){
}

val d = new Dog()val d = new Dog(age = 3);

object

单例对象,里面的成员对应java中的静态成员。 

伴生对象:companion

伴生对象和类必须位于同一个scala文件中。class Dog{}object Dog{}class Benz{    def run() = println("rrrrr...")}object Benz{    val brand = "BENZ" }

object App{
def main(args:Array[String]):Unit = {
println(“hello world”)
}
}

idea下卸载插件

设置 -->plugin -> 搜索scaal -> uninstall

idea下安装scala插件

设置 -->plugin -> install plugin from disk ... -> 选择插件文件 -> ok -> 自动重启

class //class
object //static
trait(特质) //interface

idea下创建scala模块

//接口
trait USB{
def play()
}

//伴生对象
object Benz{
//apply方法
def apply(a:String) = new Benz(a) ;
}

Benz(“black”)

隐式导入

import scala._
import java.lang._
import Predef._ //定义了很多类的别名
//type String = java.lang.String

//继承
abstract class Animal{
def eat()
}
class Dog extends Animal{
def eat();
}

//类型检查
o instanceof Car //判断是否属于Car类型
(Car)o //强转

//scala
val a = “abc”
a.isInstanceOf[String] //o instanceof Car
val b = a.asInstanceOf[String] //(Car)o

classOf[String] //Class clazz = String.class

//继承类传参父类主构造
class Benz(var color:String) {
def run() = {
println(“run…”)
}
}

class MSDS(color:String ) extends Benz(color){

}

scala类结构图

Any
|—AnyValue
final abstract class Byte private extends AnyVal
final abstract class Int private extends AnyVal
final abstract class Long private extends AnyVal
final abstract class … private extends AnyVal
final abstract class Unit private extends AnyVal //不代表任何对象,等于void
|—AnyRef
XxxClass

Null类型, 只有一个值null
val e:Null = null ; //ok
val e:Int = null ; //wrong

Nothing理解所有类的子类

Nil === List[Nothing]
Nothing是类型,没有值。
val l : List[Int] = 1 :: 2 :: Nil
val l1 : List[String] = Nil == List[Nothing]
val l1 : List[Int] = Nil == List[Nothing]
val l1 : List[Long] = Nil == List[Nothing]

:Unit = ()
Null = null
Nothing

序列化

java :java.io.Serializablescala:scala.Serializable

//调用shell脚本
import sys.prcoess._
“ls -al /” ! //linux
“dir d:/downloads” ! //windows

trait

trait White{}trait Rich{}trait Beau{}trait WB extends White with Beauti with Rich{}class WomanStar extends WB with Rich{    def rich(): Unit = ???    def white(): Unit = ???    def beauti(): Unit = ???}

自身类型:self-type
trait Elec{
this:Benz =>
}

只有Benz类或者子类才能实现该接口

操作符

[中置操作符]
1 to 10
1 -> 10

[一元操作符]
1 toString
1.toString

+a-a              //a.unary_-~a             //a.unary_~

运算符结合性

Nil == List[Nothing]1 :: Nil        //Nil.::(1) 1::2::3::Nil    //Nil.::(3).::(2).::(1)

apply() / update()

f(a,b,c)        //f.applay(a,b,c)f(a,b,c) = x    //f.update(a,b,c,x)
//class Fraction(n:Int,d:Int) {}object Fraction{    def apply(n:Int,b:Int) = new Fraction(n,b)}
//apply方法/**  * 定义伴生对象  */class Fraction(var n:Int,var d:Int) {    def *(b: Fraction) = {        Fraction(b.n * n , b.d * d)    }    override def toString = {        n + "/" + d    }}object Fraction{    def apply(n:Int,b:Int) = new Fraction(n,b)}object App{    def main(args: Array[String]): Unit = {        val f1 = Fraction(1,2)        val f2 = Fraction(1,3)        println(f1 * f2)    }}

class Option
object None extends Option[Nothing] //null
case class Some extends Option[??]

//unapply()是apply()相反过程,反解析object Fraction{    def apply(n:Int,b:Int) = new Fraction(n,b)    def unapply(f:Fraction) = {        if(f.d == 0) None else Some((f.n , f.d))    }}object App{    def main(args: Array[String]): Unit = {        val f1 = Fraction(1,2)        val f2 = Fraction(1,0)        val f3 = f1.*(f2)        //反解析        val Fraction(a,b) = f3        //常规手段调用unapply()        val r:Option[(Int,Int)] = Fraction.unapply(f3)        if(!r.isEmpty){            println(r.get._1)        }    }}

//函数
一种映射关系,从指定类型到指定类型之间的一种关系

//高级函数
函数的参数或者返回值还是函数.

import scala.math._
val f = ceil _
f(3.14)

def x2(n:Int) = n * 2
Array(1,2,3,4).map(x2)
Array(1,2,3,4).map(x2 _) //
Array(1,2,3,4).map((x:Int) => x * 2) //匿名函数

val f = (x:Int) => x * 2
Array(1,2,3,4).map(f) //

//定义高阶函数
def op(f:(Int,Int)=>Int,a:Int,b:Int) = f(a,b)

def add(a:Int,b:Int) = a + b
op(add,1,2)

op((a:Int,b:Int)=>a + b,1,2)
op((a,b)=>a + b,1,2)

def x2(n:Int) = n * 2
Array(1,2,3,4).map((x:Int)=>x * 2); //
Array(1,2,3,4).map((x)=>x * 2); //
Array(1,2,3,4).map(x=>x * 2); //
Array(1,2,3,4).map(_ * 2); //

定义返回值是函数

def tt(n:Int): Int=>Int  = {(x:Int)=> n * x }def tt(n:Int) = {(x:Int)=> n * x }