Hello! I'm beginning my first Kotlin course and I'...
# getting-started
u
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:
Copy code
val myNewObject = NewObject(x,y,z)
Method 2:
Copy code
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
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
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
welcome, it's a delightful field and kotlin is a lot of fun 🙂