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
3 Answers
+ 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