Why should we specify the data type of a variable declared in Kotlin but not yet initialized? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why should we specify the data type of a variable declared in Kotlin but not yet initialized?

Consider this code snippet: fun main() { var num: Int num = 45 } Why should we specify the type of the variable here? Why doesn't the compiler automatically determine the type of 'num' here and generate the JVM bytecode? 'num' actually holds the reference to the Int object '45' present in the heap. So is the type needed because every object takes a different amount of memory and the compiler should "know" how many bytes to read from the reference? Sorry if the last question seems a bit noob.

15th Jul 2021, 7:50 AM
Calvin Thomas
Calvin Thomas - avatar
1 Answer
+ 1
Martin Taylor Thank you, as I didn't know about that. Is String an object in Kotlin? Jazz Thank you, I understand how it's up to the designer to add features (probably because it's hard to do so).
15th Jul 2021, 10:59 AM
Calvin Thomas
Calvin Thomas - avatar