抽象类和接口的合体trait 1
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 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 = {
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
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 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)
}
偏函数
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"))
}
}