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
Rewrote pattern matching tour #717
Conversation
25abb84
to
5a83b9b
Compare
--- | ||
|
||
Scala has a built-in general pattern matching mechanism. It allows to match on any sort of data with a first-match policy. | ||
Here is a small example which shows how to match against an integer value: | ||
Pattern matching is a mechanism for checking a value for a pattern. It is a more powerful version of the `switch` statement in Java and it can likewise be used in place of a series of if/else statements. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggested for the first sentence:
Pattern matching is a mechanism for checking a value against a pattern. A successful match can also deconstruct a value into its constituent parts.
println(matchTest(3)) | ||
import scala.util.Random | ||
|
||
val x: Int = new Random().nextInt(10) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
you don't need new
here. Random.nextInt(10)
works
## Matching on type | ||
It is also possible to match on type. | ||
```tut | ||
def printType(x: Any): Unit = x match { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ten minutes til @tpolecat shows up and asks if we have to use an example based on Any
.
I'm not really sure what the right way to handle this is. The feature exists, it definitely should be included in this section of the tour, and we don't want to say it's always bad, but we don't want to give the impression that matching on Any
is normal, either. perhaps up above, before showing case class extraction, you could show something like:
notification match {
case e: Email => "you've got mail: $e"
case s: SMS => "someone texted you: $s"
case v: VoiceRecording => "check your voicemail: $v"
}
and then quickly move on and say "but most of the time, you don't just want to know what type something is, you want to do something with the individual fields, too", and then show the unapply-based version?
leaving the existing progression alone but just coming up with a non-Any
based example also seems like a possibility?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
5307c73
to
26a3013
Compare
26a3013
to
6f1aed2
Compare
@heathermiller ready to merge |
No description provided.