Android is known for its dreaded NullPointerExceptions. In this video, learn how Kotlin helps to address this issue. Look at the type system, named parameters, default values, and more.
- [Instructor] The introduction of null into programing languages has been called the billion dollar mistake. This is becuase it has led to endless errors and crashes over the past several decades. Kotlin's type system aims to address this issue by putting null ability front and center. The Kotlin compiler enforces that variables that cannot hold null values will cause a compilation error if you attempt to set them to null. Just like what we see here.
Conversely, if you explicitly declare that the variable can be nullable, you're good to go. This can prevent you from experiencing the dreaded null pointer exceptions that Android is notoriously known for. Kotlin also helps with readability in your Android code. Android tends to make liberal use of callbacks or listeners. Here's an example of setting a ClickListener on a FloatingActionButton in Java. And here it is again in Kotlin.
Much more concise, and easier to read. Another very common issue on Android is having methods with too many parameters, often of the same type. This makes it difficult to quickly scan a method and understand what values are being set. Kotlin tackles this issue by means of named parameters and default values. In this example, we have a method that we're using to order ice cream. Each parameter has a name.
And we've established, by means of default values, that we want all the fancy toppings. So when it comes time to call this method, it's very clear what values we're setting, and the code is simple and easy to read. Kotlin also allows you to extend functionality of existing classes. Even they're not your own. For instance, one common thing we do often in Android is set the visibility of a particular view. Since it's so common, you can encapsulate this code inside of an extension method on the view class.
Just like you see here. Now, instead of the call to this set visibility method, we have a simpler call to the visible method. This is a simple example. But just imagine all of the other possibilities for simplifying code by means of extension methods. In fact, Anko and Android extensions, are both examples of libraries that make heavy use of extensions and create wrappers around Android APIs, to simplify development.
Yes, when it comes to developing on Android, Kotlin has a lot to offer.
- What Kotlin has to offer
- Working with lambdas
- Common Android extension functions
- Kotlin Android Extensions overview
- Making use of the Anko library
- Working with coroutines
- Nullability and collections