https://kotlinlang.org logo
#android
Title
# android
t

Tim

11/11/2019, 2:56 PM
whats the difference between these two ways of instantiating a string?
j

joeykaan

11/11/2019, 2:59 PM
stringy2 actually has the type of optional string right, while stringy1 is a String, so it would make working with the
stringy1
easier
👍 1
r

Rob Murdock

11/11/2019, 2:59 PM
The first variable will infer its type, which will be “String” (aka the non-nullable version) The second has to have it declared, and because the type is String?, will require null checks in order to use
t

Tim

11/11/2019, 3:00 PM
ohh okay thats not what i was expected, i was actually asking in regards to when/how they are instantiated. like, are they done at the same time? i know java doesnt have the
init
method as far as im aware so im just curious what it does/when i should be concerned with it
g

gian

11/11/2019, 3:02 PM
They are instantiated in order of appearance
👍 4
j

joeykaan

11/11/2019, 3:03 PM
If you're using Android Studio (which I assume you are) if you go to Tools > Kotlin > Show Kotlin Bytecode and then check the IR checkbox and then Decompile again
👍 1
You can see the java code that is generated 🙂, that might help you to see the difference (if any)
t

Tim

11/11/2019, 3:03 PM
oh sick! thank you
😃 3
p

Paul Woitaschek

11/11/2019, 4:03 PM
You can also make
stringy2
not nullable and initialize it in the init block
a

Alowaniak

11/11/2019, 4:32 PM
Java has
initializers
, which can be static or not. The non static ones are pretty much the same as kotlin's
init
afaik.
👍 1