Why do Kotlin vars need to have a type assigned?

In the Kotlin lesson to initialize variables (https://www.codecademy.com/courses/learn-kotlin/lessons/kotlin-data-types-variables/exercises/declaring-a-variable) it tells us that when you initiate a variable you must format it as such:

var todaysDate: String = "11/02/2020"

I don’t understand the need for it. Simply declaring it as

var todaysDate = "11/02/2020"

prints the variable just the same. Is this to lock the variable to a data type?

Edit: It can’t be to lock it to a certain data type, as, after some testing, even without declaring the type, it still won’t let you assign, for example an integer to a string variable. So what purpose does that serve?

1 Like

You don’t have to (Kotlin has type inference if you are immediately initializing the variable), but it is good practice to.

In Kotlin, you are required to specify a variable’s type when you define the variable but don’t yet assign it a value:

val c: Int  // Type required when no initializer is provided

And also when you define parameters for a function:

fun sum(a: Int, b: Int): Int {
    return a + b
}

So you might as well just get in the habit of remembering to specify types even when it isn’t necessary.

Another reason why it might be a good idea is because there might be times when you assume Kotlin will infer one type but it infers a different type.

For example, you might expect your variable has an inferred type of Float, and then write a function that takes a Float, only to find out later that your variable has an inferred type Double (or vice versa).

3 Likes

Hi, @ajax0370057080
Nice question.

var todaysDate: String = “11/02/2020”

The short answer:
To be able for a null var to have interoperability with Java.

2 Likes