is there a simpler way to write this: ``` r...
# codereview
c
is there a simpler way to write this:
Copy code
return if (value != null)
            (value as Number).toDouble()
        else
            null
(not
(value as? Number).toDouble()
, which acts differently)
w
(value as? Number)?.toDouble()
c
i want it to throw if value is not null and not a number instance
w
Copy code
return value?.let { (it as Number).toDouble() }
Would be something like this?
c
that would work, but is it better than the if?
(value? as Number)
would be great
w
Copy code
fun asas1(value: Any?): Double? {
    return value?.let { (it as Number).toDouble() }
}

fun asas2(value: Any?): Double? {
    return if (value != null)
        (value as Number).toDouble()
    else
        null
}
Generates:
Copy code
@Nullable
public final Double asas1(@Nullable Object value) {
   Double var10000;
   if (value != null) {
      boolean var3 = false;
      boolean var4 = false;
      int var6 = false;
      if (value == null) {
         throw new NullPointerException("null cannot be cast to non-null type kotlin.Number");
      }

      var10000 = ((Number)value).doubleValue();
   } else {
      var10000 = null;
   }

   return var10000;
}

@Nullable
public final Double asas2(@Nullable Object value) {
   return value != null ? ((Number)value).doubleValue() : null;
}
So I would say to use the
if
🙃
j
What about
(value as Number?)?.toDouble()
?
c
thanks!!
i knew i was missing something
k
Once the JIT Sees the asas1 code it should be able to optimize it to be the the same