Skip to content

Bug in unapply #1061

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 21, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions _tour/extractor-objects.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}

Expand All @@ -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()`.
Expand Down