36

Pattern matching by Cottand · Pull Request #213 · Kotlin/KEEP · GitHub

 4 years ago
source link: https://github.com/Kotlin/KEEP/pull/213
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
ProposalThe goal of this proposal is to bring full blown pattern matching to Kotlin.Pattern matching is a tried and tested feature of many languages, such as Haskell, Rust, Scala, Ruby, and in the near future, Java.In a nutshell, it is a quick and intuitive way of checking whether an object is of some type, and to extract and check its contents. The propsal aims to do this through the existing is and destructuring componentN() semantics.Pattern matching is a major addition to a language, and as such several aspects of the proposal are up to debate. Discussion and contributions are welcome.Here is a short example of what Kotlin with pattern matching could look like:sealed class Downloaddata class App(val name: String, val developer: Person) : Download()data class Movie(val title: String, val director: Person) : Download()val download: Download = // ...// Without pattern matching:val result = when(download) { is App -> { val (name, dev) = download when(dev) { is Person -> if(dev.name == "Alice") "Alice's app $name" else "Not by Alice" else -> "Not by Alice" } } is Movie -> { val (title, diretor) = download if (director.name == "Alice") { "Alice's movie $title" } else { "Not by Alice" } }}// With pattern matching:val result = when(download) { is App(name, Person("Alice", _)) -> "Alice's app $name" is Movie(title, Person("Alice", _)) -> "Alice's movie $title" is App, Movie -> "Not by Alice"}For more details, you can read a rendered version of the proposal here.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK