Because I extracted `val isString`, `x` inside the...
# announcements
e
Because I extracted
val isString
,
x
inside the if-statement cannot be smart cast to `String`:
Copy code
val x: Any = "foo"
val isString = x is String
if (isString) {
    x + "bar" // Error, cannot smart cast x to String
}
val y = isString
Which of the following two options is preferred and why, or is there another idiomatic way to do this? 🅰️:
Copy code
val x: Any = "foo"
val isString = x is String
if (isString) {
    x as String + "bar" // Dumb cast x to String
}
val y = isString
🅱️:
Copy code
val x: Any = "foo"
if (x is String) {
    x + "bar"
}
val y = x is String // Repeat the type check
You can vote 🅰️, 🅱️, or reply in the thread for reasons why (not) to go for 🅰️ or 🅱️, or another option. Thanks! 🙂
Yet another option, an if-else expression:
Copy code
val x: Any = "foo"
val y = if (x is String) {
    x + "bar"
    true
} else {
    false
}
Which isn't pretty either (and can get ugly if the vertical distance between
val y
and the returned values becomes too large.
The vertical distance can, to some extent, be solved by splitting declaration and assignment:
Copy code
val x: Any = "foo"
val y: Boolean
if (x is String) {
    x + "bar"
    y = true
} else {
    y = false
}
But the downside is that the linter shows you a warning that the assignment can be lifted out of the if-else expression. 🤦‍♂️
w
Can use the `as?`:
Copy code
@Test
    fun checkTrue() {
        val x: Any = "foo"
        val y: Boolean = (x as? String)?.plus("bar")?.let { true } ?: false
        assertTrue(y)
    }

    @Test
    fun checkFalse() {
        val x: Any = 1
        val y: Boolean = (x as? String)?.plus("bar")?.let { true } ?: false
        assertFalse(y)
    }
Or a `let`:
Copy code
val y: Boolean = (x as? String)?.let {
            it + "bar"
            true 
        } ?: false
m
just doing a random
it + "bar"
makes it harder to understand what your goal is, but I prefer a when
Copy code
val y = when(x){
        is String -> {
            x + "bar"
            true
        }
        else -> false
    }
e
What I meant was just a side effect on
x
as a
String
Thanks for the suggestions guys