Improve smart casting by "dragging a value" along with a new ">:" drag operator

Another frequent use case is when casting a modifiable property.
The proposed syntax:

if (val x is myClass)
  x.doSomething()

instead of the current

if (x is myClass)
  (x as myClass).doSomething()

or the “idiomatic” form we tend to use:

val x = x
if (x is myClass)
  x.doSomething()

Our code is peppered with these silly val x = x lines. :frowning:

You might want to try: (x as? myClass).let { it.doSomething() }

2 Likes

Thank you, I am aware of the alternative ways of writing this (as one might expect in this forum).
Our code is obviously a bit more complex (with multiple variables) than the simple examples above; I’m looking for something more readable than having series of lambdas with let/run/also in which we have to rename the various “it” back to the name of the variable to continue making sense.
Which of the following do you prefer?

(x as? xClass)?.let { x ->
    (y as? yClass)?.let { y -> 
        x.doSomething(y)
    }
}

or

if (val x is xClass && val y is yClass)
    x.doSomething(y)

Our current code would probably create local copies of the properties:

val x = x
val y = y
if (x is xClass && y is yClass)
    x.doSomething(y)

Yes and no.

if val blah = something {
}

is the equivalent of statements:

val blah = something

if blah != null {
}

so (simpleton that I am), wouldn’t the compiler just desugar it into the two part statement? so flow control is the same.

I would say, that you shouldn’t adopt the additional syntaxes that swift also allows, with the comma separated and or the no parenthesis. Requiring parenthesis would make it more clear and allow for easier management of the flow control and determining what needs to be desugared.

1 Like

Think the syntax for those should be more along the lines of:

if (val x as? MyClass) {
x.doSomehting().
}

in current code if you are only doing something though, you can right:

(x as? MyClass)?.let {
it.doSomething().
}

which is not as clean, but not that bad.

My whole complaint about the .let{} function syntax is the lack of return.