Chapter 11 pg. 227, no 'else' statement

I noticed that in writing the ‘if’ statement for initializing the repository there is no ‘else’ keyword used. Am I missing something. I guess I just don’t understand the logic yet.

companion object{
private var INSTANCE : CrimeRepository? = null

//okay so far.

fun initialize(context: Context) {
if(INSTANCE ==null) {
INSTANCE = CrimeRepository(context)
}
}

//this makes sense, but where is the ‘else’ clause???

You would write the else clause only if you wanted to do something when INSTANCE was not null.

For example:

fun initialize(context: Context) {
      if (INSTANCE == null) {
         INSTANCE = CrimeRepository(context)
      }
      else {
         // CrimeRepository instance already initialized
         celebrate ()
      }
}
1 Like

You must not be familiar with programming languages. Not all if-else statements need an else because it means it only do one thing and if this. you would only use an else statement if you want the program to do something else if the if statement fails the conditions.