https://kotlinlang.org logo
Title
u

Uberunix

04/13/2020, 5:05 PM
Hello! I'm beginning my first Kotlin course and I'm confused about the creation of objects. The instructor has created them in two different ways Method 1:
val myNewObject = NewObject(x,y,z)
Method 2:
val myNewObject: NewOject = NewObject(x,y,z)
Is there a practical reason that he declared the type of "myNewObject" in certain cases? It seems unnecessary.
a

Adam Powell

04/13/2020, 5:13 PM
without further surrounding context and assuming this code appears either in a function body or at the top level of a file it is indeed unnecessary here. You are required to declare the types of parameters explicitly, which means you could see code like the second in a class's primary constructor with a default value for the parameter.
Also, if you're assigning a more specific object to a more general interface or base class type, it's sometimes useful to be explicit like this. Same for some edge cases around getting type inference to do what you want where something might be ambiguous otherwise. I wouldn't worry about that too much just yet though.
u

Uberunix

04/13/2020, 5:16 PM
Thank you for the explanation! I apologize for not supplying more context. I'm familiar with basic programming concepts to a degree, but mostly new to the pursuit as a whole.
a

Adam Powell

04/13/2020, 5:16 PM
welcome, it's a delightful field and kotlin is a lot of fun 🙂