Can anybody think why this resolves to type `Any?`...
# announcements
t
Can anybody think why this resolves to type
Any?
instead of
Number?
Copy code
fun String.toNumber(): Number? = toIntOrNull() ?: toLongOrNull() ?: toBigIntegerOrNull()
m
Inference bug? Since it doesn't complain when you define it explicitly.
h
I'd Imagine it has something to do with
Int
,
Long
inheriting from kotlin's
Number
, which does not inherit from java's, which
BigInteger
does.
but as you pointed out.
BigInteger("123") is Number
resolves to true, and I have no idea why that is
t
BTW, you can fix the line above by putting
as Number?
after
toLongOrNull()
. (Not after
toBigIntegerOrNull()
as you might expect.)
v
I think Int and Long inherits from Kotlin's Number but whereas Biginteger Inherits from Java Number class. Therefore theyare 2 different classes. Hence it resolves to Any
@Hullaballoonatic Please check your ' is' check. That must have imported from Java Number so its returning true
t
No, it's not. Without any import,
BigInteger("123") is kotlin.Number
returns
true
. It is a great mystery to me why that is, but it is. See here: https://pl.kotl.in/32qL74dYR
m
@Toddobryan maybe you posted the wrong snippet? That code seems about a totally different topic…. (the operator get() trick is so cool, btw! 😉 )
v
@Toddobryan Can you please check it again. Cause the BigInteger extends fron Java Number where as Int extends from Kotlin Number class Thats why it resolves to any. May be I am wrong but still Its good to recheck
t
Copy code
/**
 * You can edit, run, and share this code. 
 * <http://play.kotlinlang.org|play.kotlinlang.org> 
 *
 */

import java.math.BigInteger

fun main() {
    print(BigInteger("123") is kotlin.Number)
}
This is what that link sends me to. https://pl.kotl.in/32qL74dYR And it prints
true
.
m
weird… now it works! Yesterday I swear it displayed different code 🙂 Thanks