what’s the default/suggested/safest/recommended wa...
# getting-started
o
what’s the default/suggested/safest/recommended way to initialize stuff like this ? http://snpy.in/kISHVt
i
You can use default values for
String
and
Int
or
lateinit
for non primitives.
Copy code
lateinit var smth: String
var smth: String = ""
var smth: Int = 0
o
this is the way to go isn’t it?
only in Kotlin do I find myself resorting to this ? = null initialization
because it’s allowing me to set anything as a defualt value null
so I think it’s the safest since the option is now open to me, I start thinking that yea an Int could be sent to me as null
i
Then you need to decide if you want to be defensive or offensive when receive null
d
all values are optional? is this a data class?
👍 1
Are you planing to use jackson with it? because you can set default values in jackson and there's no need to set defaults in data class
n
If you have an
init { }
block in the class, you can just make them all
val thing: String
and it won’t complain because they will always be initialized
Otherwise: The
var thing: String? = null
is basically the equivalent in Java because anything can be null. You’re just forced to acknowledge it in Kotlin.
You could use a
data class
. That screenshot only shows a bunch of properties, which data classes are perfect for wrapping. Assuming this isn’t a huge class with lots of methods.
o
why would I use a data class?
sorry for the extremely late answer, but a data class will offer you a hash and equals methods no?
what’s the value here, but good point for init!
during testing, I need these values to be initialized all auotmatically so that I can instantiate objects of this class with the fields I want, i dont wanna run around and have them all filled before i get the chance to use the class
n
Ah, the reason I suggested a data class is in that screenshot I didn’t see any functions, just data. So I was thinking you could have a
data class
for all of that.
Copy code
data class ClassConfig(...)
class MyClass {
    val config = ClassConfig(
        ....
    )
    // Functions here...
}