Erik
04/03/2020, 10:21 AMval isString
, x
inside the if-statement cannot be smart cast to `String`:
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?
🅰️:
val x: Any = "foo"
val isString = x is String
if (isString) {
x as String + "bar" // Dumb cast x to String
}
val y = isString
🅱️:
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! 🙂Erik
04/03/2020, 10:23 AMval 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.Erik
04/03/2020, 10:25 AMval 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. 🤦♂️wbertan
04/03/2020, 10:32 AM@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)
}
wbertan
04/03/2020, 10:33 AMval y: Boolean = (x as? String)?.let {
it + "bar"
true
} ?: false
Michael de Kaste
04/03/2020, 11:17 AMit + "bar"
makes it harder to understand what your goal is, but I prefer a when
val y = when(x){
is String -> {
x + "bar"
true
}
else -> false
}
Erik
04/03/2020, 11:21 AMx
as a String
Erik
04/03/2020, 11:22 AM