Imagine you have a sealed class Foo, with `class Bar(x: String) : Foo()` and `Baz() : Foo()`.
Now, imagine you have a method, returning an object of type Foo: `fun foo(): Foo`
And you want to pattern match on the result of this method:
when(foo()) {
is Bar -> ...
is Baz -> ...
}
Now, the problem is: how do you access String field x in the first branch? The only way to do it now is to extract the methos call into redundant local variable, and then pattern match it instead of `foo()` directly as I did above.Now imagine Kotlin had that feature; then we could just do the following:
when(foo = foo()) {
is Bar -> foo.x
is Baz -> ...
} match foo() {
Bar @ foo => foo.x,
Baz => ...,
}What I'm thinking of here is Rust's match statements, which do give you the ability to make use of those intermediary values by making use of Rust's enum type.
https://doc.rust-lang.org/book/second-edition/ch06-02-match....
if(malloc(10000 * sizeof foo) == NULL) {
// Error processing
} // No need for an else branch here. int success = NULL;
if(success = malloc(...)) {
}
if(success = malloc(...)) {
}
if(success = malloc(...)) {
} char* p = NULL;
if (p = malloc(...)) {
...
}Conditionals need an expression, and assignment fits the bill, so it works.
No, but it has a lot to do with the way humans write code. This is the source of the bug, not the logic. eg Why bother having whitespace that the compiler can't use (typically)? Human readability.
The concession to not take into account human failing, is pathological.
guard let value = myOptional else {
// Handle absence
}
// Use value
Or if let value = myOptional {
// Use value
}It's very good.