From c5f969a36221a23b224700d2020cf59951d2aec9 Mon Sep 17 00:00:00 2001 From: luiru72 Date: Thu, 26 Apr 2018 12:58:34 +0200 Subject: [PATCH 1/2] Bug in unapply Split always returns a head, so None is never returned in the original code. The proposed change checks whether there is more than one element. --- _tour/extractor-objects.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/_tour/extractor-objects.md b/_tour/extractor-objects.md index db8ee5bbbf..cb0b57bdcd 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 } } From 4de0733d3476f49660c1419bbc8ec64229801828 Mon Sep 17 00:00:00 2001 From: luiru72 Date: Thu, 26 Apr 2018 15:26:42 +0200 Subject: [PATCH 2/2] Modified example according to code changes --- _tour/extractor-objects.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/_tour/extractor-objects.md b/_tour/extractor-objects.md index cb0b57bdcd..a1cd0b2fae 100644 --- a/_tour/extractor-objects.md +++ b/_tour/extractor-objects.md @@ -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()`.