https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

Daniel Branco

09/11/2021, 10:01 AM
Hey guys! I am at the very beginning of using Kotlin and understanding certain mechanics, if I have the following:
Copy code
data class Foo(
   var id: Int?, 
   var name: String = "bar", 
   var anotherVar
)
I thought I could have calls like
Foo()
or
Foo(id=1)
without needing to pass all the parameters to the constructor, am I wrong? Where can I read more about constructors in Kotlin?
e

ephemient

09/11/2021, 10:06 AM
the same applies to all callables (functions), not just constructors: all parameters must either be specified or have a default value (or both, in which case the specified value is used rather than the default)
since there's no default on
id
or
anotherVar
, both must be specified
also, because
name
is optional and precedes a required argument,
anotherVar
must be given by name if
name
is omitted
d

Daniel Branco

09/11/2021, 10:29 AM
Thanks @ephemient
s

Stephan Schroeder

09/11/2021, 7:13 PM
Also
anotherVar
needs a type. Candiates: •
Any
or
Any?
(like
Any
but nullable) if you want to put anything in it. • Or you make
Foo
generic:
Copy code
data class Foo<T> {
   var id: Int?, 
   var name: String = "bar", 
   var anotherVar: T
)
but since you're new to Kotlin maybe generics are too advanced??
1
3 Views