Monday, January 11, 2016

Scala extractors

/**
  * Created by kaiyin on 1/10/16.
  */
object TestUnapply {
  case class Division(val number: Int) {
    def unapply(divider: Int): Option[(Int, Int)] = if (number % divider == 0) Some(number/divider, 0) else None
    def unapply(divider: Double): Boolean = number % divider.toInt == 0
  }


  val divisionOf15 = Division(15)
  val y = 5 match {
    case divisionOf15(z, w) => s"$z, $w"
    case _ => s"Not divisible"
  }

  val z = 5.0 match {
    case divisionOf15() => "Divisible"
    case _ => "Not divisible"
  }
}

0 comments: