scala04 高级特性

 trait 类的多继承

package com.csg

//scala高级特性
object test08 {
  trait Person1{
    def person1Say: Unit ={
      println(s"person1 ---say ")
    }
    def personsay()
  }
  trait Person2{
    def person2Say: Unit ={
      println(s"person2 ---say ")
    }
  }
  class Person3 extends Person1 with Person2 {
    def person3Say: Unit ={
      println(s"person3 ---say ")
    }

    override def personsay(): Unit = {
      println(s"override ---say ")
    }
  }

  def main(args: Array[String]): Unit = {
    val person3 = new Person3()
    person3.person1Say
    person3.person2Say
    person3.person3Say
    person3.personsay()
  }

}

case 类型 可以判断数据是否相等一般用在判断内容,如果没有case 则输出false false有的话输出true true

package com.csg

object test09 {
  case class Person1(name:String,age:Int){
  }

  def main(args: Array[String]): Unit = {
    val person1 = new Person1("zhangsan",15)
    val person2 = new Person1("zhangsan",15)
    println(person1.equals(person2))
    println(person1==person2)
  }
}

match 方法 println 返回Unit 会有()打印

package com.csg

object t4est10 {
  def main(args: Array[String]): Unit = {
    val tp1 = (1.0, "123", 10, false,33)
    val iterator = tp1.productIterator
    val value = iterator.map(
      x => x match {
        case a:Double => println(s"$a is Double")
        case 10 => println(s"$x is 10")
        case a:Int => println(s"$a is Int")
        case a:Int  if a<50 => println(s"$a <50")
        case _ => println(s"$x is any")
      }
    )
    while(value.hasNext)println(value.next())
  }
}

偏函数  使函数更加简洁。。输入一个int 返回一个String的偏函数

package com.csg

object test11 {
  def main(args: Array[String]): Unit = {
    val value : PartialFunction[Int,String]={
      case 1 =>"一"
      case 2 =>"二"
      case 3 =>"三"
      case 4 =>"四"
      case _ =>"其他"
    }

    println(value(1))
  }
}

隐式转换--隐式参数

package com.csg

object test12 {
  def saySomething(age:Int)(implicit a:String): Unit ={
    println(s"say---  $a age is $age")
  }
  def main(args: Array[String]): Unit = {

    implicit val name:String ="zhangsan"
    saySomething(15)
  }
}

隐式函数,使函数具备其他功能 ,其实是根据传入参数的类型找到最近的隐式函数 并执行 

package com.csg

object test13 {
  class Animal(name:String){
    def canEat(): Unit ={
      println(s"$name can eat ...")
    }
  }
  class Bird(xname:String){
    val name = xname
    def canFly(): Unit ={
      println(s"$name can Fly ...")
    }
  }

  def main(args: Array[String]): Unit = {
    implicit def asd(bird:Bird): Animal ={
    new Animal(bird.name)
    }

    val bird = new Bird("鸟")
    bird.canFly()
    bird.canEat()
  }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值