

Android goodies will not be given to that student and if he is enrolled in the Android batch then we will give Android goodies to him. If he is not enrolled in the Android batch then null will be returned i.e. So, we will first check if the student is of Android batch or not.

Only when the value of studentA is not null otherwise it will return null. So, to handle these type of situations, we use Safe calls(?.). StudentA.giveGoodies() //will show compilation error Now if we want to give goodies of Android batch to student A then it will show NullPointerException because the student is of DS batch and we are giving goodies of Android batch. In Android is null(as he is not in Android batch). "is in the DS batch(and not in Android) so, the value of student So, before distributing the goodies we need to check if the student is enrolled (not null) in a particular batch or not(null). In general, it is possible that a student enrolled in Android batch is not enrolled in DS batch. we have different goodies for Android, Kotlin and DS. Now, we at MindOrks decided to distribute some goodies to the students enrolled in our courses but the goodies are course-specific i.e. So, suppose we are having one database that stores all the students enrolled in a particular course. As you all know that in MindOrks, we provide training on Android, Kotlin and Data Structure. Let’s see how we can use them and what’s the difference between these two.īefore diving into safe calls, let’s take an example.

But what if there are so many variables and you need to check if they all are null or not? You have to write a number of if-else statements for the same :( Don’t be sad, you need not write if-else statements.įor the same work. Yeah, this method can be used for checking the null values. Following is the code that is in your mind: The very common and mostly used method of checking the nullability is by using if-else :) Yes, you guess it right. If it is null then you should show some relevant error message and if it is not null then you can do the operation that you want to perform on that property. So, it becomes necessary to check if the property that you or any other developer is going to use is null or not. Var name: String? = "MindOrks" //no error Sign to the type of the variable as shown below: Var name: String = null //compilation error Name = null //compilation error // other way We can’t use the following syntax in Kotlin: If you are doing so then you will get compile-time error.

So, in Kotlin, a normal property can’t hold a null value. If you are familiar with Java, then must have encountered withĪnd to remove this or in other words, we can say that to safely deal with this NullPointerException, the developers of Kotlin introduced Null safety. Null safety is one of the best features of Kotlin.
