Reputation: 845
I am writing a Kotlin application, I've been studying this language for a little bit and I noticed that to create a variable you have to explicitly define if it can be null and then you use the ? operator.
Now, my question. Sometimes I have to define a global variable (a Fragment in this case), so I need to make it null, because I cannot initialize it yet
In java I don't have this problem because the first thing I do after declaring it is initializing in the onCreate() like this
TurboFragment fragment = null;
@Override
public void onCreate(Bundle savedInstanceState) {
...
fragment = adapter.getCurrentFragment();
}
And then I can use it without syntax problems In Kotlin is different, because I have to do like that
private var fragment: TurboFragment? = null
override fun onCreate(savedInstanceState: Bundle?) {
...
fragment = adapter!!.currentFragment
fragment!!.foo()
var x = fragment!!.sampleInt
}
Now, every time I call an instance of fragment i have to use the null-safe !! operator. This makes my code a mess, because for every line I have at least one !! operator and it looks really unclear if it's so frequent, especially if you have 5 or more variables like that. Is there a way to simplify the code or the nature of this language is like that?
Upvotes: 4
Views: 188
Reputation: 11963
Consider using Late-Initialized Properties. They're intended for your use-case.
private lateinit var fragment: TurboFragment
However, you should keep in mind that accessing a lateinit
property before it has been initialized throws an exception. That means you should use them only if you are absolutely sure, they will be initialized.
print(fragment) // UninitializedPropertyAccessException is thrown
Upvotes: 6