Is it necessary to specify the type in this case: ...
# announcements
m
Is it necessary to specify the type in this case:
Copy code
var x = 10
var z: Long = x.toLong()
// or can I just write var z as:
var z = x.toLong()
// compiler should be able to infer the type, no?
s
Is it necessary to specify the type in this case
no
// compiler should be able to infer the type, no?
yes
are you asking because you’re seeing behavior that suggests otherwise
m
I just saw this code in my book and it seemed redundant to specify the type, but as a beginner, I wasn't sure if this was best practice or how it should be written.
Is there a way to quickly check the type in Kotlin? I had to do this in the REPL and do a if (z is Long) { println("z is Long") }
I'm more familiar with JavaScript which has .typeof operator to check the type really quickly.
s
there is an intention for this
Screen Shot 2020-04-22 at 3.03.11 PM.png
with your text cursor placed after the variable name, bring up the intentions menu (alt/option+enter on macos) and select the appropriate type hints intention to see them at a glance
m
You just blew my mind. That's awesome. Thank you!
👍 1
s
also, you can get the runtime type of a variable (albeit without generics) by getting its class reference, e.g.
Copy code
val foo = 42.toLong()
println(foo::class)   // class kotlin.Long
👍 1
m
That's really cool. This is going to speed up my learning a lot. Really appreciate it!
s
and it might be worth mentioning that if you explicitly need a
Long
and are specifying a literal for it, you don’t have to call
.toLong()
- just append
L
to it:
val foo = 42L
. integer literals that are greater than
2³¹ - 1
are automatically allocated as
Long
s — see the docs: https://kotlinlang.org/docs/reference/basic-types.html
👍 1
happy to help 👍
m
The book is good, but now I understand it better with your help 🙂 Thanks again!
💯 1