Scala语法基础

1、scala下载

下载安装包直接安装

2、配置环境变量

path里面添加$SCALA_HOME/bin

3、idea环境配置

直接安装scala插件

4、变量声明

val表示常量,大型系统设计开发时,通常将传递给其他模块的对象设计为不可变。var表示变量

val result = 1+1 存放计算结果

val result =2

val name:String =null

val name,name1:String=null

5、数值类型

Byte Short Integer Long Double Float String Char

6、操作符

跟java基本一致除了无++,--

7、函数调用

除了无参数是不用加括号,其余和java一样

apply函数,通常采用这个构造对象。String中采用apply求底层字符

8、循环

只有while循环和简单for循环

var n = 10 for(i<-1 to 10){println((i+1))}

多重for循环

for(i<-1 to 9;j<-1 to 9){

  if(j==9){

    println(i*j)

  }else{

    print(i*j+" ")

  }

}

if守卫

for(i<-1 to 100 if i %2=0){

  println(i)

}

 for推导式,构造集合

for(i<-1 to 100){

 yield i

}

9、函数,=号表示有返回值,无返回值的称为过程

def sayHello(name:String,age:Int)={

  if(age > 18){

  printf("Hi,%s,hi you are a boy",name)

  age

}else{

  printf("Hi,%s,hi you are a children",name)

  age

}

}

def fab(n:Int):Int={
    if(n<=0) 1
    else fab(n-1)+fab(n-2)
}

 10、参数默认值,带名参数,未命名参数必须放左边

def sayHello(firstName:String,middleName:String=""){
    print(firstName + " "+ middleName)
}

sayHello("杨春",middleName="chun")

变长参数,展开range序列

def sum(nums:Int*):Int={
    var result = 0
    for(n <- nums){
        result +=n
    }
    result
}

sum(1 to 5:_*)
def sum(nums:Int*):Int={

  if(nums.length==0) 0
   else nums.head + sum(nums.tail:_*)
}
 

11、lazy,第一次试用变量时才会计算

lazy val line  = fromFile("")

12、异常捕获

try{
    throw new IllegaArgumentException("illegal argument")
}catch(){
    case _:IllegaArgumentException =>print("abc")
    
}finally{
    print("abc")
}

 13、数组

val a = new Array[String](10)

val a = Array("hello","world")

val a = Array("hello",30) 数组公共类型Any

可变数组

ArrayBuffer

val b = ArrayBuffer[Int]()

b +=1 添加元素

b +=(2,3,4,5) 添加多个元素

b++=Array(6,7,8,9,10)

b.trimEnd(5)从尾部截断几个

b.insert(5,6)指定位置插入

b.remove(1)

b.remove(1,3)指定位置移除几个元素

a.toBuffer

b.toArray

for(i<-0 until b.length)

  println(b(i))

for(i<-0 until (b.length,2))

  println(b(i))

for(i<-(0 until b.length).reverse)

  println(b(i))

for( e<-b)

  println(e)

val sum = a.sum

val max = a.max

a.mkString(",")逗号分隔

a.mkString("(",",",")")

 

val a = Array(1,2,3,4,5)

val a2 =for(e<-a) yield e*e

val b = new ArrayBuffer[Int]()

val b2 = for(e<-b) yield e*e

val b3 = for(e<-b if e%2=0) yield e*e

a.filter(_%2=0).map(2*_)

a.filter{_%2=0}.map{2*_}

 

算法题移除掉第一个负数以后的所有负数,移动n次元素

val a = new ArrayBuffer[Int]()

a+=(1,2,3,4,5,-1.-3,-5,-9)

var fundFirstNegative =false

var arrayLength  = a.length

var index =0

while(index <arrayLength){

  if(a(index) > =0){

    index+=1

  }

  else{

    if(!fundFirstNegative){

      fundFirstNegative = true

      index+=1

    }else{

      a.remove(index)

      arrayLength -=1

    }

  }

}

 

性能优化后,只移动一次元素

var fundFirstNegative =false

val keepIndexes = for(i<-0 until a.length if !fundFirstNegative ||a[i]>=0) yield {

   if(a[i]<0){

    fundFirstNegative = true 

    i

 }

}

for(i<-0 until keepIndexes.length){a(i)=a(keepIndexes(i))}

a.trimEnd(a.length-keepIndexes.length)

 

14、map与tuple

map默认不可变

val map = Map("Leo" -> 30,"Jack" -> 25,"Jen" -> 25)

val ages = scala.collection.mutable.Map("Leo" -> 30,"Jack" -> 25,"Jen" -> 25)

val map = Map(("Leo" ,30),("Jack" ,25),("Jen",25))

val ages = scala.collection.mutable.HashMap[String,Int]

ages("Leo") = 41

ages+=("yang"->31,"Tom"->34)

ages-=("yang")

更新不可变map,生成一个新的map

val ages2 = ages +("yang"->31,"Tom",34)

 

map的遍历

for((key,value)<-ages) println(key+" "+value)

for(key<-ages.keySet) println(key)

for(value<-ages.values) println(value)

for((key,value)<-ages) yield(value,key)

 

sortMap,自动按key排序

val ages = scala.collection.mutable.SortedMap("Leo" -> 30,"Jack" -> 25,"Jen" -> 25)

LinkedMap,记住插入顺序

val ages = scala.collection.mutable.LinkedHashMap[String,Int]

ages("leo")=30

ages("alice")=15

ages("jen")=25

 

Map的元素类型

val t = ("leo",30)

t._1

val names = Array("leo","jack","mike")

val ages = Array(30,24,26)

val nameAges = names.zip(ages)

for((name,age)<-nameAges) println(name+":"+age)

var t2 =("leo",30,"yang")

 

14、面向对象

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-28 13:04 
 */
class HelloWorld {
  private var name ="yangchun"
  def sayHello(){println("Hello,"+name)}
  def getName = name
}
package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-28 13:05 
 */
object Test {
  def main(args: Array[String]): Unit = {
      var helloWorld = new HelloWorld
      helloWorld.sayHello()
      helloWorld.getName
  }
}

定义为var的类变量是会自动生成setter和getter方法

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-28 13:05 
 */
object Test {
  def main(args: Array[String]): Unit = {
      var helloWorld = new HelloWorld
      helloWorld.sayHello()
      helloWorld.getName
      var student = new Student
      println(student.name)
      student.name = "jack"
      println(student.name)
  }
}

自己定义getter和setter方法

class Student2 {
  private var myName ="yangchun"
  def name="your name is" +myName
  def name_=(newName:String): Unit ={
    println("you can not edit your name")
  }
}
package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-28 13:30 
 */
class Student3 {
  private var myAge = 0
  def age_=(newAge:Int): Unit ={
    if(newAge>0){
      myAge = newAge
    }else{
      println("Illegal age")
    }
  }
  def age=myAge
  def older(s:Student3)={
    myAge > s.age
  }
}
package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-28 13:05 
 */
object Test {
  def main(args: Array[String]): Unit = {
      var helloWorld = new HelloWorld
      helloWorld.sayHello()
      helloWorld.getName
      var student = new Student
      println(student.name)
      student.name = "jack"
      println(student.name)
      var student3 = new Student3
      var student4 = new Student3
      student3.age =25
      println(student3.age)
      student4.age =40;
      println(student4.age)
      println(student3.older(student4))
  }
}

 如果不希望类成员变量被其他对象访问

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-28 13:30 
 */
class Student3 {
  private[this] var myAge = 0
  def age_=(newAge:Int): Unit ={
    if(newAge>0){
      myAge = newAge
    }else{
      println("Illegal age")
    }
  }
  def age=myAge
  def older(s:Student3)={
    myAge > s.age
  }
}

java风格的getter和setter

package com.xiaofeiyang.test

import scala.beans.BeanProperty


/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-28 18:16 
 */
class Student4 {
  @BeanProperty var name:String =_
}
package com.xiaofeiyang.test

import scala.beans.BeanProperty

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-28 18:20 
 */
class Student5(@BeanProperty var name:String)
package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-28 13:05 
 */
object Test {
  def main(args: Array[String]): Unit = {
      var helloWorld = new HelloWorld
      helloWorld.sayHello()
      helloWorld.getName
      var student = new Student
      println(student.name)
      student.name = "jack"
      println(student.name)
      var student3 = new Student3
      var student4 = new Student3
      student3.age =25
      println(student3.age)
      student4.age =40;
      println(student4.age)
      println(student3.older(student4))
      var student6 = new Student4
      println(student6.getName)
  }
}

15、构造函数,要么互相调用要么调用默认构造造函数

辅助构造函数

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-28 18:24 
 */
class Student6 {
  private var name = ""
  private var age =0
  def this(name:String){
    this()
    this.name = name;
  }
  def this(name:String,age:Int){
    this(name)
    this.age =age;
  }
}

主构造函数

package com.xiaofeiyang.test

/**
* @author: yangchun
* @description:
* @date: Created in 2020-04-28 18:24
*/
class Student6(var name:String ="yangchun",var age:Int=12) {
def this(name:String){
this()
this.name = name;
}
}

15、内部类,每个对象的内部类都不是同一个内部类

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-28 13:05 
 */
object Test {
  def main(args: Array[String]): Unit = {
        val c1 = new Class
        val s1 = c1.getStudent("leo")
        c1.students+=s1
        val c2 = new Class
        val s2 = c2.getStudent("leo")
        c2.students+=s2
       // c1.students += s2编译不过
  }
}
package com.xiaofeiyang.test

import scala.collection.mutable.ArrayBuffer

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-28 18:36 
 */
class Class {
  class Student(val name:String){

  }
  val students = new ArrayBuffer[Student]
  def getStudent(name:String)={
    new Student(name)
  }
}

 16、object,单个实例,通常在里面放一些静态的field或者method。通常作为单例模式的实现和类的静态成员变量,比如工具方法。

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 7:06 
 */
object Person {
  private var eyeNum = 2
  println("this person object!")
  def getEyeNum = eyeNum
}

17、伴生对象,class和object同名,互相可以访问private变量

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 7:14 
 */
class Person2(val name:String,val age:Int) {
  def sayHello = println("Hi,"+name+",I know you are"+age+" years old"+",and usually you must have "+ Person2.eyeNum +" eyes")
}
object Person2{
  private val eyeNum =2
  def getEyeNum = eyeNum
}

18、oject继承抽象类

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 7:24 
 */
abstract class Person3(var message:String){
  def sayHello(name:String):Unit
}
object Person3 extends Person3("yangchun"){
  override def sayHello(name: String): Unit = {
    println("name:"+name)
  }
}

19、apply方法

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 7:27 
 */
class Person4(val name:String) {

}
object Person4{
  def apply(name: String): Person4 = new Person4(name)
}

var person = Person4("leo")

20、主函数第二种写法

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 7:34 
 */
object Test2 extends App {
  if(args.length>0) println("Hello "+args(0))
  else println("Hell World")
}

21、枚举

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 7:38 
 */
object Season extends Enumeration {
  val SPRING,SUMMER,AUTUMN,WINTER = Value
}
package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 7:40 
 */
object Season2 extends Enumeration {
  val SPRING = Value(0,"spring")
  val SUMMER = Value(1,"summer")
  val AUTUMN = Value(2,"autumn")
  val WINTER = Value(3,"WINTER")
}
package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 7:34 
 */
object Test2 extends App {
  if(args.length>0) println("Hello "+args(0))
  else println("Hell World")
  println(Season(1))
  println(Season2.withName("spring"))
  for(ele<-Season2.values)
    println(ele)
}

 22、继承

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 11:09 
 */
class Person5 {
  private var name = "leo"
  def getName = name
}
package com.xiaofeiyang.test

class Student7 extends Person5{
  private var score = "A"
  def getScore = score
}

package com.xiaofeiyang.test

class Student7 extends Person5{
private var score = "A"
def getScore = score

override def getName: String = "hi,"+super.getName
}
 

覆盖属性

package com.xiaofeiyang.test

class Student7 extends Person5{
  private var score = "A"
  def getScore = score
  override var name:String="leo"
  override def getName: String = "hi,"+super.getName
}

23 isInstanceOf 和 asInstanceOf,类型判断和转换

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-28 13:05 
 */
object Test {
  def main(args: Array[String]): Unit = {
        val person = new Person5
        val student = new Student7
        println(student.getScore)
        println(student.getName)
        var s:Student7 =null
        if(student.isInstanceOf[Student7]) s= student.asInstanceOf[Student7]
  }
}
package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-28 13:05 
 */
object Test {
  def main(args: Array[String]): Unit = {
        val person = new Person5
        val student = new Student7
        println(student.getScore)
        println(student.getName)
        var s:Student7 =null
        if(student.isInstanceOf[Student7]) s= student.asInstanceOf[Student7]
        println(student.getClass == classOf[Person5])
  }
}
package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-28 13:05
 */
object Test {
  def main(args: Array[String]): Unit = {
        val person = new Person5
        val student = new Student7
        println(student.getScore)
        println(student.getName)
        var s:Student7 =null
        if(student.isInstanceOf[Student7]) s= student.asInstanceOf[Student7]
        println(student.getClass == classOf[Person5])
        student match {
          case person5: Person5 =>println("it's Person's object")
          case _ =>println("unknown type")
        }
  }
}

24 protected关键字来修饰field和method,子类可以直接访问,protectedthis只有自己子类对象才可以访问

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 13:35 
 */
class Person6 {
  protected var  name ="leo"
  protected var age =30
}
class Student8 extends Person6{
  def sayHello = println("hello:"+name)
  def makeFriends(s:Student8): Unit ={
    println("my age is"+age)
    //println("your age is"+s.age),编译不过
  }
}

25、主构造函数

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 13:45 
 */
class Animal(val name:String,val age:Int) {

}
class Dog(name:String,age:Int,var score:Double) extends Animal(name,age){
  def this(name:String){
    this(name,0,0)
  }
  def this(age:Int){
    this("leo",age,0)
  }
}

26、匿名内部类

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 13:56 
 */
class Person7(protected val name:String) {
    def sayHello ="Hello,I'm "+name
}
package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-28 13:05
 */
object Test {
  def main(args: Array[String]): Unit = {
        val p = new Person7("leo"){
          override def sayHello = "I,am "+name
        }
  }
}

27、抽象类抽象字段

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 14:06 
 */
abstract class Animal2 {
  val name:String
}
class Dog2 extends Animal2{
  val name:String ="gou2"
}

 28、trait作为接口使用

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 15:27 
 */
trait MakeFriendsTrait {
  def makeFriendsTrait(p:Person)
}
trait HelloTrait {
  def sayHello(name:String)
}
class Person(val name:String) extends MakeFriendsTrait  with HelloTrait {
  override def makeFriendsTrait(p: Person): Unit = println("hello,"+p.name)

  override def sayHello(name: String): Unit = println("hello,my name is "+name)
}

trait存放具体方法实现

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 15:27 
 */
trait MakeFriendsTrait {
  def makeFriendsTrait(p:Person)
}
trait HelloTrait {
  def sayHello(name:String)
}
trait logger{
  def info(message:String)=println("log is:"+message)
}
class Person(val name:String) extends MakeFriendsTrait  with HelloTrait with logger {
  override def makeFriendsTrait(p: Person): Unit = println("hello,"+p.name)

  override def sayHello(name: String){
    println("hello,my name is "+name)
    info(name)
  }

}

trait定义field和继承父类field不一样

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 15:27 
 */
trait MakeFriendsTrait {
  def makeFriendsTrait(p:Person)
}
trait HelloTrait {
  def sayHello(name:String)
}
trait logger{
  def info(message:String)=println("log is:"+message)
}
trait eye{
  val eyeNum:Int=2
}
class Person(val name:String) extends MakeFriendsTrait  with HelloTrait with logger with eye{
  override def makeFriendsTrait(p: Person): Unit = println("hello,"+p.name)

  override def sayHello(name: String){
    println("hello,my name is "+name)
    info(name)
  }
  def calcEyeNum(){
    println(eyeNum)
  }
}

给类混入trait

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:06 
 */
trait MyLogger extends Logged{
  override def log(msg: String)= println(msg)
}
class MyLoggerImpl(val name:String) extends Logged {
  def sayHello: Unit ={
    println("Hi,I'm "+name)
    log(name)
  }
}

trait Logged{
  def log(msg:String){}
}

trait调用链

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:20 
 */
trait Handler {
  def handle(msg:String){

  }
}
trait DataValidHandler extends Handler {
  override def handle(msg: String){
    println("check msg")
    super.handle(msg)
  }
}
trait Signature extends Handler {
  override def handle(msg: String){
    println("signature msg")
    super.handle(msg)
  }
}

class HandlerImpl extends Signature with DataValidHandler {
  def sayHello(name:String): Unit ={
    println("hello:"+name)
    handle(name)
  }
}
Hi,I'm yangchun
yangchun
hello:yangchun
check msg
signature msg

Process finished with exit code 0

trait具体方法和抽象方法混合使用

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:31 
 */
trait Valid {
  def getName:String
  def valid:Boolean=getName=="leo"
}
class ValidImpl(val name:String) extends Valid{
  println(valid)
  override def getName=name
}

trait构造代码,不在任何方法里面的代码就是构造函数。从左到右一直调用

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:06 
 */
trait MyLogger extends Logged{
  println("MyLogger construct")
}
trait TimeLogger extends Logged{
  println("TimeLogger construct")
}
class MyLoggerImpl() extends MyLoggerImplFather with MyLogger  with TimeLogger {
  println("myLoggerImpl construct")
}

trait Logged{
  println("logged construct")
}

class MyLoggerImplFather{
  println("myloggerImplFather construct")
}
myloggerImplFather construct
logged construct
MyLogger construct
TimeLogger construct
myLoggerImpl construct

trait field的初始化

会报空指针异常

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 17:33 
 */
trait TraitField {
  val msg:String
  println("msg:"+msg.toString)
}
class TraitTest extends TraitField{
   val msg: String = "init"
}

提前混入一个msg

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13 
 */
object Test{
  def main(args: Array[String]): Unit = {
    val TraitTest = new {override val msg:String="tiqian"} with TraitTest with TraitField
  }
}

定义的时候混入一个

trait TraitField {
  val msg:String
  println("msg:"+msg.toString)
}
class TraitTest extends {
    val msg: String = "init"
} with TraitField

使用lazy

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 17:33 
 */
trait TraitField {
  lazy val msg:String = null
  println("msg:"+msg.toString)
}
class TraitTest extends TraitField {
    override lazy val msg: String = "init"
} 

28、trait继承class

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 17:44 
 */
class MyUtil{
  def printMessage(msg:String)=println("msg:"+msg)
}
trait HeritUtil extends MyUtil{
  def log(msg:String)=printMessage(msg)
}
class TraitHeritClass(val msg:String)extends HeritUtil {
  def sayHello: Unit ={
    log("hi,this is"+msg)
    printMessage("hi,myUtil is"+msg)
  }
}

 29、Scala函数编程,独立定义函数

def sayHello(name:String)=println("hello:"+name)
    var sayHelloFunc = sayHello _
    sayHelloFunc("leo")

匿名函数

 var sayHiFunc = (name:String)=>println("hi:"+name)
    sayHiFunc("leo")

高阶函数就是将函数作为返回值

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13 
 */
object Test{
  def main(args: Array[String]): Unit = {
    val traitHeritClass = new TraitHeritClass("yangchu")
    traitHeritClass.sayHello
    def sayHello(name:String)=println("hello:"+name)
    var sayHelloFunc = sayHello _
    sayHelloFunc("leo")
    var sayHiFunc = (name:String)=>println("hi:"+name)
    sayHiFunc("leo")
    def greeting(func:(String)=>Unit,name:String){func(name)}
    greeting(sayHelloFunc,"yangchun")
    greeting(sayHiFunc,"lidan")
  }
}
 Array(1,2,3,4,5).map((num:Int)=>num*num)

高阶函数返回一个匿名函数

def getGreetingFunc(msg:String)=(name:String)=>println(msg+","+name)
    val greetingHello = getGreetingFunc("Hello")
    val greetingHi = getGreetingFunc("Hi")
    greetingHello("leo")
    greetingHi("leo")

高阶函数可以自动推断参数类型

package com.xiaofeiyang.test

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13 
 */
object Test{
  def main(args: Array[String]): Unit = {
    val traitHeritClass = new TraitHeritClass("yangchu")
    traitHeritClass.sayHello
    def sayHello(name:String)=println("hello:"+name)
    var sayHelloFunc = sayHello _
    sayHelloFunc("leo")
    var sayHiFunc = (name:String)=>println("hi:"+name)
    sayHiFunc("leo")
    def greeting(func:(String)=>Unit,name:String){func(name)}
    greeting(sayHelloFunc,"yangchun")
    greeting(sayHiFunc,"lidan")
    Array(1,2,3,4,5).map((num:Int)=>num*num)
    def getGreetingFunc(msg:String)=(name:String)=>println(msg+","+name)
    val greetingHello = getGreetingFunc("Hello")
    val greetingHi = getGreetingFunc("Hi")
    greetingHello("leo")
    greetingHi("leo")
    greeting((name)=>println("haha"+name),"yangchun")
    greeting(name=>println("haha"+name),"yangchun")
  }
}
def triple(func:(Int)=>Int)={func(3)}
    println(triple(3*_))
 println(Array(1,2,3,4,5).map(2*_))

    (1 to 9 ).map("*" * _).foreach(println _)
 (1 to 9 ).map("*" * _).foreach(println _)
    (1 to 20).filter(_ %2==0)
    (1 to 9 ).reduceLeft(_*_)
    Array(1,2,3,4,5).sortWith(_ < _)

30、闭包,函数在变量不属于其作用域范围时,还能对其进行访问。msg作为函数的局部变量,在getGreetingFunc执行完成后,还存在创建的函数中,调用时值为hello的msg被保留在函数体内部,可以反复使用

 def getGreetingFunc(msg:String)=(name:String)=>println(msg+","+name)
    val greetingHello = getGreetingFunc("Hello")
    val greetingHi = getGreetingFunc("Hi")
    greetingHello("leo")
    greetingHi("leo")

 31、SAM 转换,匿名函数转换成类

package com.xiaofeiyang.test

import java.awt.event.{ActionEvent, ActionListener}

import javax.swing.JButton

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13 
 */
object Test{
  def main(args: Array[String]): Unit = {
    val button  = new JButton()
    button.addActionListener(new ActionListener {
      override def actionPerformed(e: ActionEvent): Unit = println("click me")
    })
    implicit def getActionListener(actionProcFunc:(ActionEvent=>Unit))=new ActionListener {
      override def actionPerformed(e: ActionEvent) {actionProcFunc(e)}
    }
    button.addActionListener((event:ActionEvent)=>println("click me"))
  }
}

32、Currying函数

package com.xiaofeiyang.test

import java.awt.event.{ActionEvent, ActionListener}

import javax.swing.JButton

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13 
 */
object Test{
  def main(args: Array[String]): Unit = {
    def sum(a:Int,b:Int) = a+b
    def sum2(a:Int) = (b:Int)=>a+b
    def sum3(a:Int)(b:Int)=a+b
  }
}

33、return在匿名函数里面返回值,作为带名函数的返回值

package com.xiaofeiyang.test

import java.awt.event.{ActionEvent, ActionListener}

import javax.swing.JButton

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13 
 */
object Test{
  def main(args: Array[String]): Unit = {
    def greeting(name:String)={
      def sayHello(name:String):String={
        return "Hello:"+name
      }
      sayHello("yangchun")
    }
  }
}

34、集合操作

Iterable,Seq,Set,Map,Iterable是所有trait的根trait。集合分为可变不可变,mutable和unmutable。Seq是所有range,array,list,ArrayBuffer的根trait

list

package com.xiaofeiyang.test

import java.awt.event.{ActionEvent, ActionListener}

import javax.swing.JButton

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13 
 */
object Test{
  def main(args: Array[String]): Unit = {
    val list = List(1,2,3,4,5)//不可变
    println(list.head)
    println(list.tail)//不包含第一个元素
    val list2 = -1::list//合并
    def decorator(I:List[Int],prefix:String): Unit ={
      if(I!=Nil){
        println(prefix+I.head)
        decorator(I.tail,prefix)
      }
    }
    decorator(list,"*")
  }
}

 LinkedHashSet

package com.xiaofeiyang.test

import scala.collection.mutable

/**
* @author: yangchun
* @description:
* @date: Created in 2020-04-29 16:13
*/
object Test{
def main(args: Array[String]): Unit = {
var set = mutable.LinkedHashSet(1,2,3,4)
set+=5
set.foreach(println(_))
var set2 = mutable.SortedSet(2,3,4,1)
set2.foreach(println(_))
}
}

函数式编程

 var list = List("aiden yang","orion liu","horny guan").flatMap(_.split(" "))
    list.map(println(_))
    var list2 = List("aiden yang","orion liu","horny guan").map("my name is"+_)
    list2.map(println(_))
    var list3 = List("aiden yang","orion liu","horny guan").zip(List(100,60,70))
    list3.map(println(_))

小案例单词数量统计

   var file1 = scala.io.Source.fromFile("d://tes1.txt").mkString
    var file2 = scala.io.Source.fromFile("d://tes2.txt").mkString
    val lines = List(file1,file2)
    println(lines.flatMap(_.split(" ")).map((_,1)).map(_._2).reduceLeft(_ + _))

 35、模式匹配

可以匹配值,可以匹配类型,有没有值匹配

基础语法

package com.xiaofeiyang.test

import scala.collection.mutable

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13 
 */
object Test{
  def main(args: Array[String]): Unit = {
    def judgeGrade(score:String): Unit ={
      score match {
        case "A" =>println("Excellent")
        case "B" =>println("Good")
        case "C" =>println("Just so so")
        case _ =>println("you need to work harder")
      }
    }
    judgeGrade("A")
  }
}

升级版本,if守卫

package com.xiaofeiyang.test

import scala.collection.mutable

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13 
 */
object Test{
  def main(args: Array[String]): Unit = {
    def judgeGrade(name:String,score:String): Unit ={
      score match {
        case "A" =>println("Excellent")
        case "B" =>println("Good")
        case "C" =>println("Just so so")
        case _ if name =="leo"=>println(name+"you are a good boy, come on")
        case _ =>println("you need to work harder")
      }
    }
    judgeGrade("A","yangchun")
  }
}
package com.xiaofeiyang.test

import scala.collection.mutable

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13 
 */
object Test{
  def main(args: Array[String]): Unit = {
    def judgeGrade(name:String,score:String): Unit ={
      score match {
        case "A" =>println("Excellent")
        case "B" =>println("Good")
        case "C" =>println("Just so so")
        case _grade if name =="leo"=>println(name+"you are a good boy, you grade is"+_grade)
        case _ =>println("you need to work harder")
      }
    }
    judgeGrade("leo","F")
  }
}

 

类型匹配,异常处理

package com.xiaofeiyang.test

import java.io.{FileNotFoundException, IOException}

import scala.collection.mutable


/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13 
 */
object Test{
  def main(args: Array[String]): Unit = {
    def processException(e:Exception): Unit ={
      e match {
        case e1:IllegalArgumentException=>println("you have illegal arguments! exception is:"+e)
        case e2:FileNotFoundException=>println("file not found")
        case e3:IOException=>println("io error")
        case _:Exception=>println("unknown exception")
      }
    }
    processException(new IOException())
  }
}

 

Array和List的元素进行匹配

package com.xiaofeiyang.test

import java.io.{FileNotFoundException, IOException}

import scala.collection.mutable


/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13 
 */
object Test{
  def main(args: Array[String]): Unit = {
    def greeting(arr:Array[String]): Unit ={
      arr match {
        case Array("leo")=>println("hi,leo")
        case Array(girl1,girl2,girl3)=>println("hi,girl i know your name"+girl1+","+girl2+","+girl3)
        case Array("leo",_*)=>println("hi,leo,please introduce your friends to me")
        case stranger=>println("who are you")
      }
    }
    greeting(Array("leo"))
    greeting(Array("yanchun","lidan","yanghuan"))
    greeting(Array("leo","lidan","yanghuan","zhangwei"))
    greeting(Array("zhangjiayao"))
    def greeting2(arr:List[String]): Unit ={
      arr match {
        case "leo"::Nil=>println("hi,leo")
        case girl1::girl2::girl3=>println("hi,girl i know your name"+girl1+","+girl2+","+girl3)
        case "leo"::tail=>println("hi,leo,please introduce your friends to me")
        case _=>println("who are you")
      }
    }
    greeting2(List("leo"))
    greeting2(List("yanchun","lidan","yanghuan"))
    greeting2(List("leo","lidan","yanghuan","zhangwei"))
    greeting2(List("zhangjiayao"))
  }
}

 

case class和模式匹配,case class会自动生成getter和setter方法,自动定义伴生对象和apply方法

package com.xiaofeiyang.test




/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13 
 */

object Test{
  def main(args: Array[String]): Unit = {
    def judgeIdentify(p:person){
      p match {
        case teacher(name,subject)=>println("teacher,name is"+name+",subject is"+subject)
        case student(name,classroom)=>println("student,name is"+name+",classroom is"+classroom)
        case _=>println("illegal access ,please go out of the school")
      }
    }
    val leo:person = teacher("leo","english")
    judgeIdentify(leo)
  }
}

class person
case class student(name:String,classroom:String) extends person
case class teacher(name:String,subject:String) extends person

 

Option与模式匹配 Some表示有值,None表示没有值

 

package com.xiaofeiyang.test




/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13 
 */

object Test{
  def main(args: Array[String]): Unit = {
    val grades = Map("leo"->23,"jack"->25)
    def getGrade(name:String)={
      val grade = grades.get(name)
      grade match {
        case Some(grade)=>println(grade)
        case None=>println("none")
      }
    }
    getGrade("leo")
  }
}

 36、类型参数相当于泛型,就是类型参数,用来限制集合里面的类型

 

package com.xiaofeiyang.test




/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13 
 */

object Test{
  def main(args: Array[String]): Unit = {
    var leo = new student[Int](1)
    leo.getSchoolId(2)
  }
}

class student[T](val localId:T){
  def getSchoolId(hukould:T)="S-"+hukould+"-"+localId
}

泛型函数

package com.xiaofeiyang.test




/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13 
 */

object Test{
  def main(args: Array[String]): Unit = {
    var leo = new student[Int](1)
    leo.getSchoolId(2)
    def getCard[T](content:T)={
      if(content.isInstanceOf[Int])"card:001,"+content
      else if(content.isInstanceOf[String])"card:this is your card,"+content
      else "card:"+content
    }
    getCard[String]("hello")
    getCard[Int](100)
  }
}

class student[T](val localId:T){
  def getSchoolId(hukould:T)="S-"+hukould+"-"+localId
}

上边界,指定传入参数必须是某个类的子类


package com.xiaofeiyang.test




/**
* @author: yangchun
* @description:
* @date: Created in 2020-04-29 16:13
*/

object Test{
def main(args: Array[String]): Unit = {
def getIDCard[T >: Child](p1: T) {
if(p1.getClass==classOf[Child]) println("please tell your parents")
else if(p1.getClass==classOf[Father]) println("please sign your name")
else println("sorry,you are not allowed to get id card")
}
val child = new Child("leo")
val father = new Father("jack")
getIDCard[Child](child)
getIDCard[Father](father)
val work = new work
getIDCard(work)
}
}
class work
class Father(val name:String)
class Child(name:String)extends Father(name){
}
 

view bounds就是上下边界加强版本,支持对隐式类型进行转换,再判断是否在边界内

package com.xiaofeiyang.test




/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13 
 */

object Test {
  def main(args: Array[String]): Unit = {
    var leo = new Student("leo")
    var jack = new Student("jack")
    var party1 = new Party(leo,jack)
    party1.pay()
    var doggy = new Dog("doggy")
    var party = new Party(leo,doggy)
    party.pay()
  }
  implicit def dog2Person(dog: Object): Person = {
    if(dog.isInstanceOf[Dog]) {
      val _dog = dog.asInstanceOf[Dog];
      new Person(_dog.name)
    } else if(dog.isInstanceOf[Person]){
      dog.asInstanceOf[Person]
    }else {
      Nil
    }
  }
}
class Person(val name:String){
  def sayHello = println("Hello,I'm"+name)
  def makeFriends(p:Person): Unit ={
    sayHello
    p.sayHello
  }
}
class Student(name:String) extends Person(name)
class Dog(val name:String){def sayHello=println("Wang,Wang,I'm "+name)}

class Party[T <% Person](p1:T,p2:T){
  def pay(): Unit ={
    p2.makeFriends(p1)
  }
}

 context bounds,它基于全局上下文自动注入

package com.xiaofeiyang.test




/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13
 */

object Test {
  def main(args: Array[String]): Unit = {
    val cal = new Calculator(1,2)
    println(cal.max)
  }
}
class Calculator[T:Ordering](val num1:T,val num2:T){
  def max(implicit order:Ordering[T]) = if(order.compare(num1,num2)>0) num1 else num2
}

Manifest Context Bounds,实例化一个泛型数组

package com.xiaofeiyang.test




/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13
 */

object Test {
  def main(args: Array[String]): Unit = {
    def packageFood[T:Manifest](food:T*)={
      val foodPackage = new Array[T](food.length)
      for(i<-0 until food.length) foodPackage(i)= food(i)
      foodPackage
    }
    var yangpai = new Meat("yangpai")
    var gongbaojiding = new Meat("gongbaojiding")
    var qingcai = new Vegetable("qingcai")
    var meats = packageFood((yangpai,gongbaojiding))
    meats.foreach(println(_.))
  }
}
class Meat(val name:String)
class Vegetable(val name:String)

协变和逆变,+T就是类及子类都可以,-T就是类和父类都可以

package com.xiaofeiyang.test




/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13
 */

object Test {
  def main(args: Array[String]): Unit = {
    def enterMeet(card:Card[Master]){
      println("master enter meet")
    }
    def enterMeet2(card1:Card[Professional]){
      println("professional enter meet2")
    }
    var leo = new Card[Master]("leo")
    var jack = new Card[Professional]("jack")
    enterMeet(leo)
    enterMeet2(jack)
    enterMeet(jack)
  }
}
class Master
class Professional extends Master

class Card[+T](val name:String)
class Card1[-T](val name:String)

37、隐式转换,一般会去源类型和目标类型以及伴生对象里面查找隐式转换函数,程序当前作用域,手动import导入隐式转换函数。发生时间调用函数参数类型不一致,调用方法不存在。调用方法有该方法但是

参数不匹配

package com.xiaofeiyang.test




/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13
 */

object Test {
  def main(args: Array[String]): Unit = {
    var ticketNumber =0
    def buySpecialTicket(p:SpecialPerson)={
      ticketNumber +=1
      "T-"+ticketNumber
    }
    println(buySpecialTicket(new Student("leo")))
    println(buySpecialTicket(new Older("lidan")))
  }
  implicit def object2SpecialPerson(obj:Object):SpecialPerson={
    if(obj.getClass==classOf[Student]){
      val stu = obj.asInstanceOf[Student]
      new SpecialPerson(stu.name)
    }else if(obj.getClass==classOf[Older]){
      val older = obj.asInstanceOf[Older]
      new SpecialPerson(older.name)
    }else{
      Nil
    }
  }
}
class SpecialPerson(val name:String)
class Student(val name:String)
class Older(val name:String)

增加类功能

package com.xiaofeiyang.test




/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13
 */

object Test {
  def main(args: Array[String]): Unit = {
    var leo =new Man("leo")
    leo.emitLaser
  }
  implicit def man2Superman(man:Man):Superman={
    new Superman(man.name)
  }
}
class Man(val name:String)
class Superman(name:String) extends Man(name){
  def emitLaser = println("emit a laser")
}
package com.xiaofeiyang.test




/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13
 */

object Test {
  def main(args: Array[String]): Unit = {
    var ticketHous = new TicketHous
    println(ticketHous.buySpecialTicket(new Student("leo")))
    println(ticketHous.buySpecialTicket(new Older("lidan")))
  }
  implicit def object2SpecialPerson(obj:Object):SpecialPerson={
    if(obj.getClass==classOf[Student]){
      val stu = obj.asInstanceOf[Student]
      new SpecialPerson(stu.name)
    }else if(obj.getClass==classOf[Older]){
      val older = obj.asInstanceOf[Older]
      new SpecialPerson(older.name)
    }else{
      Nil
    }
  }
}
class SpecialPerson(val name:String)
class Student(val name:String)
class Older(val name:String)
class TicketHous(){
  var ticketNumber =0
  def buySpecialTicket(p:SpecialPerson)={
    ticketNumber +=1
    "T-"+ticketNumber
  }
}

隐式参数

package com.xiaofeiyang.test




/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13
 */

object Test {
  def main(args: Array[String]): Unit = {
    implicit val signPe = new SignPen
    def signForExam(name:String)(implicit signPen:SignPen)={
      signPe.write(name+"welcome to exam")
    }
    signForExam("leo")
  }
}
class SignPen{
  def write(content:String)=println(content)
}

 38、actor入门,相当于java的多线程

package com.xiaofeiyang.test

import akka.actor.{Actor, ActorSystem, Props}
/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13
 */

object Test {
  private val myActorFactory = ActorSystem("myActorFactory")
  private val helloActorRef = myActorFactory.actorOf(Props[HelloActor],"helloActor")
  def main(args: Array[String]): Unit = {
    helloActorRef ! "leo"
  }
}
class HelloActor extends Actor{
  override def receive: Receive = {
    case name:String=>println("hello,"+name)
  }
}

线程之间精准通讯

package com.xiaofeiyang.test

import akka.actor.{Actor, ActorSystem, Props}
/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13
 */

object Test {
  private val myActorFactory = ActorSystem("myActorFactory")
  private val helloActorRef = myActorFactory.actorOf(Props[UserManageActor],"helloActor")
  def main(args: Array[String]): Unit = {
    helloActorRef ! Register("leo","12345")
    helloActorRef ! Login("leo","12345")
  }
}
case class Login(username:String,password:String)
case class Register(username:String,password:String)
class UserManageActor extends Actor{
  override def receive: Receive = {
    case Login(username,password)=>println("login,username "+username+" password "+password)
    case Register(username,password)=>println("register,username "+username+" password "+password)
  }
}
package com.xiaofeiyang.test

import akka.actor.{Actor, ActorRef, ActorSystem, Props}
/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-29 16:13
 */

object Test {
  private val myActorFactory = ActorSystem("myActorFactory")
  private val leoRef = myActorFactory.actorOf(Props[LeoTelePhoneActor],"leo")
  private val jackRef = myActorFactory.actorOf(Props[JackTelePhoneActor],"jack")
  def main(args: Array[String]): Unit = {
    leoRef ! Message("I'm free",jackRef)
  }
}
case class Message(content:String,sender:ActorRef)
class LeoTelePhoneActor extends Actor{
  override def receive: Receive = {
    case Message(content,sender)=>println("leo telephone:"+content);
      sender ! "I am leo,please call me later"
  }
}
class JackTelePhoneActor extends Actor{
  override def receive: Receive = {
    case response:String=>println("jack telephone:"+response)
  }
}

 

posted on 2020-04-25 22:02  清浊  阅读(252)  评论(0编辑  收藏  举报