21偏函数

本文最后更新于 2021-08-05 11:42:59

偏函数

有点像filter+map

//偏函数
object PartialDemo {

  def main(args: Array[String]): Unit = {
    val list = List(1,2,3,"123",true)

    //定义偏函数
    //偏函数的意思就是满足  isDefinedAt方法的元素,执行apply
    //偏爱!
    val f = new PartialFunction[Any,Int] {
      override def isDefinedAt(x: Any): Boolean = x.isInstanceOf[Int]

      override def apply(v1: Any): Int = v1.asInstanceOf[Int]
    }


    val res=  list.collect(f)

    println(res)
    //List(1, 2, 3)
  }

简单版

object PartialDemo2 {

  def main(args: Array[String]): Unit = {
    val list = List(1,2,3,"123",true)

    val a = list.collect({
      case a:Int =>a
      case _=>0
    })
    println(a)
  }
}
object PartialDemo3 {

  def main(args: Array[String]): Unit = {
    val m = Map(1->"a",2->"b")
    m.foreach(x=>{
      println(x._1)
      println(x._2)
    })
    //偏函数
    m.foreach({
      case (a,b)=> println(a)
    })
   
  }
}
//偏函数
object PartialDemo4 {

  def main(args: Array[String]): Unit = {
    val list = List((1, (2, 3)), (4, (5, 7)))
    
    //想获取2和5
    //可读性高
    val res1 = list.map(_._2._1)
    val res2 = list.map({
      case (a, (b, c)) => b
    })

  }
}

21偏函数
https://jiajun.xyz/2020/11/18/scala/21偏函数/
作者
Lambda
发布于
2020年11月18日
更新于
2021年8月5日
许可协议