learning scala extracors example

object Twice {
  def apply(x: Int): Int = x * 2
  def unapply(z: Int): Option[Int] = if (z % 2 == 0) Some(z / 2) else None
}

object TwiceTest extends Application {
  val x = Twice(21)
  x match { case Twice(n) => Console.println(n) } // prints 21
}
object TwiceTest extends Application {
  val x = Twice.apply(21)
  Twice.unapply(x) match { case Some(n) => Console.println(n) } // prints 21
}

猜你喜欢

转载自www.cnblogs.com/lianghong881018/p/11355858.html