疯狂的Scala缩写和用法

2021-11-07  本文已影响0人  抬头挺胸才算活着
    def addBy(a : Int) : Int => Int = a + _
    println(addBy(1)(2))
class User(val name: String, val age: Int)
object User{
  def apply(name: String, age: Int): User = new User(name, age)
  def unapply(user: User): Option[(String, Int)] = {
    if (user == null)
      None
    else
      Some(user.name, user.age)
  }
}
object TestMatchUnapply {
  def main(args: Array[String]): Unit = {
    val user: User = User("zhangsan", 11)
    val result = user match {
      case User("zhangsan", 11) => "yes"
      case _ => "no"
    }
    println(result)
  }
}
  val myRex : Regex = "([a-zA-Z]+)name_(\\d+)_id".r

  def main(args: Array[String]): Unit = {
    val rexFunc : PartialFunction[String, String] = {
      case myRex(sourceType, _) =>
        sourceType
      case _ => "not found"
    }

    val name = rexFunc("xiaoming_name_16777231_id")
    print(name)
  }

1 样例类仍然是类,和普通类相比,只是其自动生成了伴生对象,并且伴生对象中
自动提供了一些常用的方法,如 apply、unapply、toString、equals、hashCode 和 copy。
2 样例类是为模式匹配而优化的类,因为其默认提供了 unapply 方法,因此,样例
类可以直接使用模式匹配,而无需自己实现 unapply 方法。
3 构造器中的每一个参数都成为 val,除非它被显式地声明为 var(不建议这样做)

case class User(name: String, age: Int)
object TestMatchUnapply {
  def main(args: Array[String]): Unit = {
    val user: User = User("zhangsan", 11)
    val result = user match {
      case User("zhangsan", 11) => "yes"
      case _ => "no"
    }
    println(result)
  }
}
  class MyRichInt(val self: Int) {
    def myMax(i: Int): Int = {
      if (self < i) i else self
    }
    def myMin(i: Int): Int = {
      if (self < i) self else i
    }
  }
  object TestImplicitFunction {
    // 使用 implicit 关键字声明的函数称之为隐式函数
    implicit def convert(arg: Int): MyRichInt = {
      new MyRichInt(arg)
    }
    def main(args: Array[String]): Unit = {
      // 当想调用对象功能时,如果编译错误,那么编译器会尝试在当前作用域范
      // 围内查找能调用对应功能的转换规则,这个调用过程是由编译器完成的,所以称之为隐
      // 式转换。也称之为自动转换
      println(2.myMax(6))
    }
  }
上一篇 下一篇

猜你喜欢

热点阅读