, unapply of case class Tuple2.
Tuple2.unapply, , - .
null.
val str: Any = null
str match {
case _: String => "yay"
case other => "damn"
}
|-> res1: String = damn
:
val str = "HELP"
val (firstPart:String, secondPart:String) = str match {
case "NO-HELP" => ("First Help", "Second Help")
case "OTHER-HELP" => ("I won't Help!", "Even,I won't Help!")
case "HELP" => (null,"Single Help")
case _ => throw new NoSuchMethodException
}
, :
val tuple: (String, String) = str match {
case "NO-HELP" => ("First Help", "Second Help")
case "OTHER-HELP" => ("I won't Help!", "Even,I won't Help!")
case "HELP" => (null,"Single Help")
case _ => throw new NoSuchMethodException
}
unapply Tuple2. :
def unapply[A, B](tuple: Tuple2[_, _]): Option[(A, B)]
, !
,
val (first: String, second: String) = tuple
Tuple2.unapply [String, String], , (String, String).
Option[(String, String)], unapply .
, - Tuple2 , :
object Tuple2 {
def apply[A, B](_1: A, _2: B): Tuple2[A, B] = new Tuple2(_1, _2)
def unapply[A, B](tuple: Tuple2[_, _]): Option[(A, B)] = {
val a: Option[A] = tuple._1 match { case a: A => Some(a) }
val b: Option[B] = tuple._2 match { case b: B => Some(b) }
a.zip(b).headOption
}
, MatchError:
val a: Option[A] = tuple._1 match { case a: A => Some(a) }
, Tuple2, , , .
, :
val str = "HELP"
val (firstPart, secondPart) = str match {
case "NO-HELP" => ("First Help", "Second Help")
case "OTHER-HELP" => ("I won't Help!", "Even,I won't Help!")
case "HELP" => (null,"Single Help")
case _ => throw new NoSuchMethodException
}
, , , .
2
, vals , .
, .
val foo = ("lorem", 2)
val (lorem: String, bad: String) = foo
case class Bar(name: String, age: Option[Int])
val bar = Bar("Sam", None)
val Bar(name, Some(age)) = bar