diff --git a/_tour/extractor-objects.md b/_tour/extractor-objects.md index db8ee5bbbf..a1cd0b2fae 100644 --- a/_tour/extractor-objects.md +++ b/_tour/extractor-objects.md @@ -23,8 +23,8 @@ object CustomerID { def apply(name: String) = s"$name--${Random.nextLong}" def unapply(customerID: String): Option[String] = { - val name = customerID.split("--").head - if (name.nonEmpty) Some(name) else None + val stringArray: Array[String] = customerID.split("--") + if (stringArray.tail.nonEmpty) Some(stringArray.head) else None } } @@ -45,12 +45,18 @@ val CustomerID(name) = customer2ID println(name) // prints Nico ``` -This is equivalent to `val name = CustomerID.unapply(customer2ID).get`. If there is no match, a `scala.MatchError` is thrown: +This is equivalent to `val name = CustomerID.unapply(customer2ID).get`. -```tut:fail +```tut val CustomerID(name2) = "--asdfasdfasdf" ``` +If there is no match, a `scala.MatchError` is thrown: + +```tut:fail +val CustomerID(name3) = "-asdfasdfasdf" +``` + The return type of an `unapply` should be chosen as follows: * If it is just a test, return a `Boolean`. For instance `case even()`.