【Scala】9、Trait、Match、CaseClass和偏函数

抽象类和接口的合体trait 1

/*
*  1、trait不可以传参
*  2、类继承多个trait的时候  第一个关键字用extends 第二个用with
* */
trait Read{
  def read(name:String): Unit ={
    println(s"$name is reading... ")
  }
}
trait Listen{
  def listen(name:String): Unit ={
    println(s"$name is listen... ")
  }
}
class Human() extends Read with Listen {

}

object Test_Trait {
  def main(args: Array[String]): Unit = {
    val human = new Human()
    human.read("alalla")
    human.listen("lalal")
  }
}

抽象类和接口的合体trait 2


/*
*  trait类似于抽象类 可以有方法的实现 也可以只有方法的声明 子类去实现就好了
* */
trait PointEau{
  def isEqu(o:Any):Boolean
  def isNotEqu(o:Any):Boolean = !isEqu(o)
}
class Point(xx:Int,xy:Int) extends PointEau {
  val x=xx
  val y=xy

  override def isEqu(o: Any): Boolean = {
    //需要是一个点 并且x值相等
    o.isInstanceOf[Point] && o.asInstanceOf[Point].x==this.x
  }
}


object Test_Trait {
  def main(args: Array[String]): Unit = {
    val point1 = new Point(1, 2)
    val point2 = new Point(1, 4)
    println(point1.isEqu(point2))
  }
}

模式匹配Match

package com.yxx

/*
*   Match 模式匹配
*   1、case_ 匹配任何 放到最后
*   2、match即可以匹配类型 又可以匹配值
*   3、匹配过程有隐式类型的转换
*   4、从上往下匹配,匹配上了之后会自动终止
*   5、模式匹配外面的{}可以省略
* */

object Test_Natch {
  def main(args: Array[String]): Unit = {
    val tp=(1,1.2,"abc",'a',true)
    val iterator = tp.productIterator
    iterator.foreach(matchFun)
  }
  def matchFun(o:Any): Unit ={
    o match{
      case 1=>{println("这个是1")}
      case i:Double=>{println(s"这个是double 值是$i")}
      case s:String=>{println(s"这个是String 值是$s")}
      case _=>{println("No Match...")}
    }
  }
}

样例类case class

 /*
 * 使用case关键字定义的类就是样例类 他是特殊的类
 * 实现了构造函数的getter方法(因为参数默认是val的) 当参数是var的时候 还会实现参数的setter方法
 * 样例类是默认实现了toString equals  copy和hashCode方法的
 * 样例类可以new也可以不new
 * 只有构造函数的样例类 在声明的时候可以不加花括号
 * */
 case class A(name:String,age:Int){
   
 }
 def main(args: Array[String]): Unit = {
   val a1 = A("a", 1)
   val a2 = A("a", 1)
   println(a1.equals(a2))
   println(a1.toString)
 }

偏函数


/*
* 偏函数PartialFunction[A,B] 一进一出
* */
object Test_PartialFunction {
  def testPartialFunction:PartialFunction[String,Int]={
    case "a"=>1
    case "b"=>10
    case _=>1000000
  }
  def main(args: Array[String]): Unit = {
    println(testPartialFunction("aa"))
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值