Scala基础编程指南

基础知识

  • 基础知识
    • 函数定义
    • 流程控制
    • 异常处理
    • 元组
    • 数组
    • Map
    • Zip
  • 类的定义
    • 对象
    • 伴生对象
    • 构造函数
    • 内部类
    • Apply方法
  • 继承
    • 方法重写
    • 抽象类
    • 接口
    • AOP

函数定义

函数的定义以def开始。然后是函数名,跟着是括号里带有冒号分隔的参数列表如(id : Int),最后是返回类型等号。函数的每个参数都必须带有前缀冒号的类型标注,因为scala编译器无法推断函数的参数类型。

//标准函数
def addA(id : Int):Unit={
    var line = id
}
def addA(x : Int) = x +100 //匿名函数 val add = (x : Int) => x +200 //递归函数 def fac(n:Int):Int = if (n <= 0) 1 else n * fac(n - 1)

//函数的默认参数
def combine(content:String, left: String = "[", right: String = "]") = left + content +right println(combine("I love Scala")) ---->[I love Scala] println(combine("I love Scala","<",">")) ----><I love Scala> //函数的可变参数 def connected(args: Int*) = { var result =0 for(arg <- args) result += arg result }

流程控制

三元表达符

val file = if(!args.isEmpty) args(0) else "scala.txt"

for循环

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

//遍历数组
for(arg <- args){}

do while循环

var line = ""
do {
    line = readLine()
    println("Read: " + line)
} while (line != "")

异常处理

异常处理跟java类似,但是异常捕获是根据case匹配。

try {
    val half = if (n % 2 == 0) n /2 else throw 
    new RuntimeException("N must be event")
//  Use the file 
    }catch {
    case e : Exception => println("The exception is :" + e.getMessage())
    }finally{
//  close(file)
    }

元组

元组的index是从1开始的。

    val tuple =(1,2,3.14,"Rocky","Spark")

    //tuple里取第三个值
    val third = tuple._3

    //tuple里取值参数名对应的值
    val (first,second,thirda,fourth,fifth) = tuple

    //tuple里取前两个值,参数名为f1,s2
    val (f1, s2, _, _, _) = tuple

数组

数组的index是还是从0开始的。

    //创建数组
    val array = Array(1,2,3,4,5)
    val a = new Array[String](10)
    val s = Array("Hello", "World")
    s(0)

    //可变长数组
    val b = ArrayBuffer[Int]()
    b += 1                    //增加 1的元素到数组
    b += (1, 2, 3, 5)
    b ++= Array(8, 13, 21)
    b.trimEnd(5)              //删除后5位
    b.insert(2, 6)            //index,elem
    b.insert(2, 7, 8, 9)
    b.remove(2)               //删除第2位
    b.remove(2, 3)            //index,elem个数
    b.toArray                 //转换array

    //带条件的Array处理
    val c = Array(2, 3, 5, 7, 11)
    for (elem <- c if elem % 2 == 0) yield 2 * elem
    c.filter(_ % 2 == 0).map(2 * _)

    //sum,max,sort等Array处理
    var sum = Array(1, 4, 2, 3).sum            //10
    ArrayBuffer("Mary", "little", "lamb").max  //输出最长数组
    var s = Array(1, 4, 2, 3)
    val c = s.sorted                           //(1,2,3,4)
    scala.util.Sorting.quickSort(s)
    s                                          //(1,2,3,4)

    //多维数组
    val matrix = Array.ofDim[Double](3, 4) 
    matrix(2)(1) = 42

Map

    val ages = Map("Rocky" -> 27, "Spark" -> 5) 
    for((k,_) <- ages){ //_ 占位符
        println("Key is " + k)
    }

    //遍历并改变所有值
    val map = Map("book"->10,"gun"->18,"ipad"->1000)  
    for((k,v) <- map) yield (k,v * 0.9)

    //取Hadoop值没有返回0
    val hadoopScore = scores.getOrElse("Hadoop", 0)

    //Map的增删
    map += ("R" -> 9)
    map -= "book"

    //排序-只能对不可变数组排序
    scala.collection.immutable.SortedMap(immutable map)


Zip

    //symbols合并counts
    val symbols = Array("[", "-", "]")
    val counts = Array(2,5,2)
    val pairs = symbols.zip(counts)
    //Array[(String, Int)] = Array(([,2), (-,5), (],2))
    for ((x,y) <- pairs) print(x*y)

类的定义

对象

class Person { //通过scala内置的get/set方法调用 var age = 0 //通过get/set方法调用 private var name = "none" //对象私有字段,仅限于对象内直接调用 private [this] var id= 1 //懒加载-调用才会去加载 lazy val file = Source.fromFile("E://Scala.txt") //get方法 def getAge = age }

伴生对象

没有伴生类的Object叫做单例对象

class University{ val id = University.newStudenNo private var number =0 def aClass(number:Int){this.number += number} } //University类的伴生对象,主要放一些静态对象 object University{ private var studentNo = 0 def newStudenNo = { studentNo += 1 studentNo } }

构造函数

//Class()主构造器会自动创建name和age对象
class Teacher (val name : String, val age : Int){ //私有构造器 class Teacher private (val name : String, val age : Int){ println("This is the primary constructor!!!") var gender : String = _
    println(gender)

    //辅助构造器
    def this(name : String, age : Int, gender : String){ this(name, age) this.gender = gender } }

内部类

在scala里内部类是以对象的形式存在的

class Outer(val name : String){outer=> class Inner(val name : String){ def foo(b:Inner) = println ("Outer: " + outer.name + " Inner: " + b.name) } } val outer1 = new Outer("Spark") val outer2 = new Outer("Hadoop") val inner1 = new outer1.Inner("Scala") val inner2 = new outer2.Inner("Java") inner1.foo(inner1) inner2.foo(inner2)

Apply方法

调用Class和Object的apply方法

class ApplyTest{ def apply() = println("I am into Spark so much!!!") def haveATry{ println("Have a try on apply!") } } object ApplyTest{ def apply() = { println("I am into Scala so much!!!") new ApplyTest } } //调用类的apply方法 val clas = new ApplyTest clas() //调用objectapply方法 val obj = ApplyTest() 

继承

Scala中类的继承一定要继承父类的主构造器

class Person(namg : String, age : Int){ println("The primary constructor of Person") } class Worker(name : String, age : Int, val salary : Long) extends Person(name, age){ println("This is the subClass of Person, Primary constructor of Worker") }

方法重写

  override val school = "Spark"

  override def toString = "I am a Worker!" + super.sleep

抽象类

abstract class SuperTeacher(val name : String){} class TeacherForMaths(name : String) extends SuperTeacher(name){}

接口

注意接口是extends去继承的,且可以有抽象方法,还可以继承至类。多重继承不会多重构造类。

class A{} trait interface extend class A{ def function(msg : String) } //多重继承 构造顺序---->> class B extends interface with interface2 with ...{ override def function(msg : String) }

AOP

trait Action{
    def doAction } trait TBeforeAfter extends Action{ abstract override def doAction{ println{"Initialization"} super.doAction println("Destroyed") } } class Work extends Action{ override def doAction = println("Working...") } val test = new Work with TBeforeAfter test.doAction //Initialization //Working... //Destroyed 

你可能感兴趣的:(scala)