https://kotlinlang.org logo
#announcements
Title
# announcements
t

Toddobryan

11/02/2019, 2:03 AM
Can anybody think why this resolves to type
Any?
instead of
Number?
Copy code
fun String.toNumber(): Number? = toIntOrNull() ?: toLongOrNull() ?: toBigIntegerOrNull()
m

Mike

11/02/2019, 2:19 AM
Inference bug? Since it doesn't complain when you define it explicitly.
h

Hullaballoonatic

11/02/2019, 8:42 PM
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

Toddobryan

11/02/2019, 8:55 PM
BTW, you can fix the line above by putting
as Number?
after
toLongOrNull()
. (Not after
toBigIntegerOrNull()
as you might expect.)
v

vs.thaakur

11/04/2019, 5:25 AM
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

Toddobryan

11/05/2019, 4:08 AM
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

Matteo Mirk

11/05/2019, 11:20 AM
@Toddobryan maybe you posted the wrong snippet? That code seems about a totally different topic…. (the operator get() trick is so cool, btw! 😉 )
v

vs.thaakur

11/05/2019, 4:18 PM
@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

Toddobryan

11/05/2019, 5:32 PM
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

Matteo Mirk

11/06/2019, 10:47 AM
weird… now it works! Yesterday I swear it displayed different code 🙂 Thanks
3 Views