Android Dev Summit Is Coming!

Share if the site was helpful

Android Dev Summit Is Coming!

If you’re an Android junky then you’re probably still coming off of this years Google I/O high.  We saw some really cool stuff we can leverage in our apps to create great user experiences.  But the development fun is far from over.  It’s already time to mark your calendars for another big upcoming development conference: Android Dev Summit 2019.

Last Year’s Summit:

Last year at Android’s annual developer conference we saw some big changes.  These included things like App Bundles in place of old APKs to reduce the size of your app.  On average app sizes were decreased 8% and some saw much bigger changes (30+ percent!). The idea behind an App Bundle is to only download the resources needed for your specific phone/version instead of downloading everything and then using what you need.  We’ll actually be going into detail on it in another post soon.

That was a big size change, but a big code change was focused around Jetpack.  Another topic we’ll dive into further with some tutorials if you haven’t applied it yet is updating your legacy support libraries to AndroidX. Basically your app functions the same way, but moving forward things are a lot cleaner on the Android support library!

What’s Coming This Year?

Those are some good topics that you should definitely be leveraging in your apps today, but the purpose of this post is to ask what may be coming this year.  And if Google I/O is any indicator of it, then the answer is a lot.  There’s not an official roster of topics posted yet, but we’ll likely be seeing deeper dives into some of the topics covered at I/O such as Android Q gestures and dark mode. And now with Kotlin as the preferred language for Android development I’m sure we’ll see some technical dives into what’s happening under the hood.

Along with some of these unique sessions come other perks for those of you attending in person.  There will be more hands on experiences with product demos, and you’ll be able to meet with members of Android’s team and discuss topics in more detail.  If you’re interested in attending then here’s a huge plus: ITS FREE!  Yep no purchase necessary for a ticket, but you do haver to be accepted by invite, so there are no guarantees.  Still, applications are open until August 15thso I’d highly recommend applying!

We’re Almost There:

There are a plethora of changes that could get whole sessions focused around them (permission changes, internal app sharing, optimizations).  And if you want to make sure you’re up to date on it then keep an eye on our page or on the official Android Dev Summit page.  If you can’t make it in person (Cali isn’t just around the corner for some of us), then don’t worry.  All the sessions will be live streamed on the site as well.

What are you most excited about for Android Dev Summit 2019? Let us know in the comments below!

 

Using Kotlin DSL For Gradle

Share if the site was helpful

Using Kotlin DSL For Gradle

If you’re an Android developer then you’ve undoubtedly worked in the build.gradle file.  And you’ve undoubtedly wanted to throw things at your computer when it didn’t work as intended.  It’s a file (2 actually) essential to your app’s well being, but it’s written in Groovy which pretty much no one knows well.

This has created frustration for countless users when they can’t compile things correctly.  Thankfully there’s a better way, and as with most things Android the answer is Kotlin!

Kotlin Instead of Groovy:

Gradle recently released version 5.0, and along with this comes Gradle Kotlin DSL v1.0.  This is what lets us write our Gradle build scripts in Kotlin.  But before doing so we should ask if this is even a good idea.  Why would we want to write our build scripts in Kotlin?  Well for starters Groovy is a dynamically typed language (type is associated with run-time variables).  This means that it’s tough for Android Studio to warn you about much until after the script is already running.  Kotlin on the other hand is statically typed, so lots of bugs can be checked by the compiler before the script is ever run.

Along with this check comes autocomplete.  Android Studio will be able to suggest common method names and variables to you the way it already does in Kotlin or Java files you type in.  Couple this with the comfort that you already (hopefully) have with Kotlin, and it’s an instant improvement.

Prepping for the Leap:

So we’ve decided it may be worth looking into. What’s the first step? Step 1 setting yourself up to make the transition less painful.  Certain things are allowed in Groovy that aren’t in Kotlin, so if we make those conversions in the plain text, then converting the file will be easier.  One of these “things” is quotation marks. Groovy uses single quotations a lot, but those aren’t allowed in Kotlin.  So step one is replacing any single quotation marks you have with doubles.

Next you should make sure that your “apply plugin” uses are replaced with the plugin DSL block.  This is one plugin block that should encompass all of the plugins your project is using.  When your done here’s an example of what your plugins should look like:

There are unfortunately some limitations with this new plugin though, so if you encounter errors it is possible to still use the legacy plugin.

The final thing you’ll need to do is assign variables and call methods.  What I mean by this is that since Groovy doesn’t require you to explicitly write the = when declaring a variable or the () when running a method, these changes need to be made for Kotlin.  Here are a few examples:

Taking The Leap:

Ok, now we’ve made our prep changes, so hopefully things go smoothly with the actual changes.  We have three files we need to rename to include .kts. Our two build.gradle files now become build.gradle.kts, and our settings.gradle file should become settings.gradle.kts.  Rename these files and try to compile the project. Fingers crossed nothing erroneous pops up, and if that’s the case then congratulations you officially have a project running on Kotlin DSL!

These are just the basics, and I’m sure if your project is complex at all there will be a few more jumps in the process to Kotlin.  If that’s the case Gradle has documentation on their website that helps walk through how to go about some of these common changes.  I’d highly recommend checking them out if you feel lost.  And if you don’t need them, then your app should run just fine now, and any time you make changes to Gradle you can do so in Kotlin.

 

 

 

An Intro To Flutter

Share if the site was helpful

An Intro To Flutter

When Google I/O came and went in May one of the topics that captured a lot of interest was Flutter. Offering a whole new option for cross platform code, Flutter has been gaining traction over the past few years. I talked about it briefly a few weeks ago, but let’s dive more into the details of why it may be worth learning.

What is Flutter?

First, let’s get a quick primer of what Flutter actually is.  It’s a toolkit developed in 2017 by Google that allows you to write code for both Android and iOS devices.  You can write code once, and then implement it anywhere.  And by anywhere, I mean Android, iOS, web, and desktop.  Already if you’re a freelancer I’m sure you see some appeal here!

It’s written in Dart which hasn’t been too popular of a language in the past, but Flutter is breaking that trend.  It’s been featured at I/O for a few years straight now, and Google uses it for internal apps, so it’s not going away any time soon.  The framework revolves around widgets.  Everything in a Flutter app is a widget.  Widgets describe what a view should look like given its current state, and when that state changes a widget rebuilds its description.  It sounds kind of foreign until you dive in.

Let’s see some code!

I won’t waste time going through how to set up Flutter on your computer.  Here’s a good link to walk you through that (don’t worry it’s super simple).  For my personal use I’ve been using Flutter in Visual Studio Code, but you can also develop in other IDE’s such as Android Studio if you’re more comfortable with those. To get started run the command flutter create hello_world.  This will take care of everything for you creating a new application named hello_world.  To run it, type cd hello_worldto enter that directory, and then type flutter runto kick things off.

Congratulations!  You’re officially looking at your first flutter app. Whether you ran it on an iPhone or an Android device (or somewhere else) you should see an app that looks like this:

So what made this app? Well, this is from the default code that Flutter made for us.  In your navigation sidebar you should see folders for things such as android, ios, and lib.  There are some others as well, but I point these out because at its core you’ll work in the lib folder.  And the others will allow you to transport that code into iOS and Android phones. That’s REALLY oversimplifying it, but it’s not wrong!

main.dart:

Let’s open the lib folder, and inside we’ll see one file named main.dart.  This is the core of your app right now.  If you open up main.dart you’ll see what is creating the widgets currently showing on your phone.  For anyone just reading and not following along, here’s what it looks like:

In here we can see pretty hefty comments explaining everything.  The app starts by calling the method runApp() and passing in an instance of our class MyApp.  And as we can see right below that, MyApp is a StatelessWidget.  There are stateful and stateless widgets in Flutter, and we’ll go into them down the road, but for now just know what a widget is.

One really cool thing about Flutter is hot reloading.  When you want to rerun an app and see any changes you’ve made, you only have to recompile widgets that have changed their state.  The end result of this is incredibly fast reload speeds (milliseconds). Go ahead and try this out.  Under theprimarySwatchattribute change it from Colors.blue to Colors.red. Once you’ve done that save the project and in the terminal press “r”. Instantly you’ll see the theme of your app change from blue to red.  It’s really that simple to reload!

I’ve loved my experience thus far with Flutter because of the way it is structured and hot-reloading. There’s a whole world of development to explore, but if you get started and want to let us know what you like/dislike about it let us know in the comments below!

 

 

Google I/O Revisited

Share if the site was helpful

Google I/O Revisited

Last week we wrote about Google I/Ocoming to an end.  We highlighted some of the cool new features that were unveiled and explored upcoming technologies.  There was tons to show on stage, but of course it’s not magic.  Every tech innovation has logic working under the hood.  And as developer’s Google I/O is the perfect place to be to see how some of this logic works.

From A Developer’s POV:

First off, there’s a ton of other topics covered, but we’ll mainly be focusing on Android development in this post.  But don’t worry.  That still leaves us with tons of talking material!  Let’s start with the most fundamental topic of Android’s OS.  We saw Android Q up on the big stage at I/O, and with it are some new things that developers are going to need to consider when writing their code.

Permission changes are a big one.  An entire talk was dedicated to privacy changestaking place on Q, and immediately after it was another talk discussing location permission. In the past when you wanted access to a user’s location for your app you simple asked for it and they said yes or no. Q brings a 3rdoption into the mix.  It’s actually been around for a while on iOS devices, but starting on Q user’s will have two options to allow an app access to their location.  They can either say yes all the time, or they can grant permission only when an app is in use.  This way if there’s an app you don’t think should be tracking you when you’re not using it…well it won’t!

There were also sessions talking about new Q features such as gesture navigation and dark mode.  Yes, believe it or not Android is ditching the back button! Another iOS style move, but given time we may think it’s for the best.

New Ways to Develop:

The topic that has interested me the most since the end of I/O has been Flutter.  And if you haven’t heard of it before, here’s where to get started.  Flutter is an incredibly cool toolkit to help you write one codebase and run it on both iOS and Android apps.  Yep, write it once, ship it twice.  It was developed by Google in 2017 and since then the company has not stopped pushing it, so it doesn’t look like it’s about to fade away.  It allows for fast development, flexible UI’s and a new way of thinking while you code.

My favorite feature it the hot-reload.  Since you only have to compile changes you’ve made in the code, rerunning your app is insanely fast.  By insanely fast I mean less than a second.  This can allow for a whole new approach to coding as you constantly tweak minute things and hit run to instantly see how they change your app’s appearance.  Exploring it is a great way to learn.  I’ll be writing a post later this week in extensive detail on what Flutter has to offer because it’s so cool.

New Ways to Share:

From a developer’s standpoint there is more to life than just code.  You have to do something with the finished product, right?  There are people you need to share it with. Whether those are friends, work associates, or the world, the more options available to share your app the better.

We saw some cool things come in this realm at the talk “Customizable Delivery With the App Bundle and Easy Sharing of Test Builds”.  First, we saw how shrinking your app can dramatically increase the number of downloads that you get (1% increase for every 3MB your app sheds).  And with this we saw how to do just this by adopting App Bundles.

My favorite part of this talk though was about sharing test builds.  Taking things one step further than Alpha and Beta testing, you can now “upload” a build to the store and share the url with anyone you would like. The build is only accessible via that link though and doesn’t register as your regular app on the Play Store, so your secret is still safe if you’re doing internal testing.  Let’s say you want everyone at the office to give the new version a go before rubber stamping it.  This is designed for just that.

That’s a Wrap!

Wrapping up there were tons and tons of cool features from a development standpoint covered this year. And Google employees went over how to develop each one of them on stage in liver demos.  I would highly recommend checking out some of the footage if you haven’t yet.

What was your favorite part of Google I/O 2019?  Let us know in the comments below!

 

Starting the Reactive Journey

Share if the site was helpful

Starting the Reactive Journey

If you’re an Android developer, then odds are you’ve heard of RxJava.  It’s a popular library that utilizes the observer pattern.  Rx (ReactiveX) allows us to program reactively, meaning our code can be executed as events happen.  It’s tough to fully wrap your head around it at first, but once you get it your codebase can become more efficient and clean.

The Observer Pattern:

The Observer pattern (and RxJava) revolves around three key concepts.  The three O’s: observables, observers, and operators.  When combined these three allow us to emit information, modify it, and then react to it.  The best way to think about the observable pattern is to consider everything a stream. Data starts at the top of a stream and flows downhill.  On its way down things can happen to it to modify the data, and then at the bottom of the hill we use the data.

This is a high-level view of how the observer pattern works.  Think of observables as the top of the stream, operators changing the data on its way down, and observers as the bottom of the hill.  Ok, maybe this analogy will make a little more sense after you learn a little more about each of these O’s.

Observables:

An observable is something that can be observed.  It is something that emits data that we can react to.  A good example that already exists in Android is a button.  Whenever a button is pressed by the user it emits data. That data is basically just saying “I was pressed”, but it’s still data emitted from an observable!  What we do with that data is our option and none of the observable’s concern (think about the standard Android button; it just knows it was pressed, we write the logic for what it does).

So an observable is…literally something that is observable.  Real life examples could be a movie playing or a singer singing. These are things we could watch happen, but they don’t really impact us until we observe them.  Which brings us to the bottom of the stream.

Observers:

We’ll skip over operators right now and jump straight to observers because they are essential to this paradigm. So we have a movie playing already (the observable), and once we turn on the TV to watch it we have become the observer. The data (movie) is coming to us and we can react to it however we want.  Likewise, with an observer in Android we can write a function to react to the data an observable emits.

In the RxJava world observables don’t always have to emit just one piece of data, that’s the beauty of it.  They can emit thousands and thousands of pieces of data, and then observers can react to each and every piece of data if they see fit.  And just like multiple people can watch one tv, multiple observers can observe one observable.

Wrapping Up:

It’s a lot of “o” words I know, but the concept is pretty simple.  Observables emit data, observers react to it.  We’ll dive into plenty of code in part 2, so stay tuned for that as well as examples of how operators come into the mix!  RxJava takes a little while to get down, but once you do it’s too addictive to quit!

Keep The Resolutions Going With Phonlab

Share if the site was helpful

Keep The Resolutions Going With Phonlab

We’re one week into the new year, and hopefully sticking with resolutions.  The most common goals tend to revolve around exercising, eating healthier, or learning something.  We can’t help you out with the first two, but if you’re looking to pick up a new skill this year you’re in luck!

Mobile Developer Courses:

Phonlab’s Mobile Development courses offer a great affordable way to learn app development.  Whether you’re completely new to programming or looking to add a new skill to your repertoire, it’s worth it.  These courses will take you from writing your first line of code all the way up to publishing your first app on the Google Play Store or Apple App Store.

Coursework is great, but really sets Phonlab apart from other online educational materials is the personal touch.  As you’re learning you’ll undoubtedly get stuck. Instead of having to spend hours researching your issue, you’ll receive personalized support walking you through solutions.

What’s in a Lesson?

Depending on your level of dedication, you could go from never programming to publishing an app in less than a month.  And you only have a few spare hours a week, fear not!  With Phonlab’s one-time payment you get access to the coursework forever.  You can either speed through the course again and again or take your time and absorb all the knowledge it has to offer.

And that knowledge covers all the core topics in mobile development.  Whether it’s Material Design tips for how to create an aesthetic layout of images, or efficiently downloading information from online and displaying it to users, there’s a video teaching it.  These videos feature footage of apps being built in real time with audio explaining every step.  And along with the actual creations are animations helping to explain any tricky concepts.  The goal is to make it as easy as possible for you the developer.

Sign Up Today!

If you’re interested in taking your programming skills to the next level or starting at line 1, I’d definitely recommend you check out these courses.  Who knows, by the end of 2019 you may be making apps for a living.

Reduce, Reuse, RecyclerView

Share if the site was helpful

Reduce, Reuse, RecyclerView

Mobile users have developed a rigorous set of standards in the past few years.  If an app takes more than a few seconds to launch, they’re annoyed.  If a button takes more than one second to react to a click, there will be some uninstalls.  With such high expectations for performance app developers need to make sure they do everything in their power to speed up their apps. 

RecyclerView For Efficiency:

The Android OS has grown alongside user expectations.  New libraries and views have emerged to offer improvements to an app’s efficiency.  One of these that EVERY Android developer should know is the RecyclerView.  RecyclerView is (as defined byAndroid) a flexible view for providing a limited window into a large data set.

Basically, think about every list you scroll through on an app.  Odds are that list is a RecyclerView.  The idea is you can map out how large you want the space to be on a user’s screen, and then that portion of the screen will be scrollable showing a number of smaller layouts.  Each of these can be designed however you see fit. 

Think of Spotify’s list of songs in your library for example.  Each layout in the list holds TextViews displaying the song name, artist, an ImageView of the album cover, and an arrow on the right indicating you can click on it for more information.  This layout is used again and again but different information is loaded into it each time.

But How Is It Efficient?

So if you saved 2000 songs to your library then every time you open the app you’ll have to load 2000 layouts? That sounds like an awful user experience as they have to wait.  No you won’t, and that’s the beauty of a Recyclerview.  Your app is only going to create 10-15 of those layouts. Then as you scroll it will empty the top layout’s info, kick it back down to the bottom of the RecyclerView, and load it with new data. 

Your app has all the info from the list, but it only has to create views for items as they appear to the user.  And once a few views have been created, it won’t ever have to make new views since it recycles them as you scroll.  I wonder how they came up with the name RecyclerView…

Setting Up RecyclerView

Adding a RecyclerView to your app’s layout is not too complicated, but there is a fair amount of work involved.  Phonlab’s Android App Developer Course shows a detailed step by step tutorial, but we’ll cover the 30,000ft view here.  The process essentially breaks down into two parts:  Your layout and your adapter.  The layout is more straightforward; it’s you creating an xml wireframe view for where you want the info to load.  What should a layout look like when it’s given the proper info?

The adapter is a little more complicated.  There are three methods that your RecyclerView adapter will override.  These are onCreateViewHolder(), onBindViewHolder(), and getItemCount().  In order these tell your adapter what to do when creating a new layout, adding new data to a layout, and how many items are in the list total.  onCreateViewHolder will be called every time we need to make a new layout, but once the initial work is done and a user begins to scroll onBindViewHolder will be where you add click listeners and other interaction logic.

Seeing it in action:

After you have all of your logic for loading the data into a ViewHolder (layout) you need to create an instance of the RecyclerView in your app.  Then set the RecyclerView’s LayoutManager and Adapter using the class’s methods.  If everything is set up correctly and you’ve added an xml RecyclerView in your parent layout, then clicking run should show your scrollable list of views.

It’s essential your app meets current standards for efficiency.  RecyclerView is a great way to improve responsiveness.  With it you can present users with immense amounts of data without slowing down their experience at all!

Overriding and Overloading: What’s the Difference?

Share if the site was helpful

Overriding and Overloading: What’s the Difference?

When programming for Android (or anything) writing custom methods isn’t optional. If you don’t know what it means to write a method, then I recommend you check out Phonlab’s video tutorials.  And if you do, then don’t tune out yet!  Methods are like icebergs (90% of their functionality is unseen at first glimpse).  And getting to know the other 90% is what can take you to the next level in your development.  In this post we’re going to explore the ins and outs of overriding and overloading to make development easier.

Methods 101:

If you’re an Android programmer, then you undoubtedly know what a method is.  It’s a block of code that you give a name.  This way every time you call it that block is executed.  I know it’s a fundamental concept of programming, but here’s a sample that we’ll build onto over time.  Let’s say that you’re building a contacts app and can add contacts given a name and phone number.  Here’s the class your app uses:

Great, seems simple enough right?  But any good contacts app is going to do more than just this.  If a user wants, they should be allowed to include other info as well.  What if they want to put one contact on speed dial? Or what if they want to add a contact to a group?  How about this:

Now, there’s no problem with this code.  Each of these three methods will add a contact with the extra information that they included.  But these method names could start turning ugly if we kept adding parameters.  How do you feel about the method name addNewContactWithSpeedDialAndGroupAndPictureAndAgeAndRingtone?  First off, I’d say let’s drop every “And”, but even so that method name is getting long.  This is where overloading can help.

Overloading:

Overloading is the practice of creating new methods with the same name.  But you can’t have two identical method names, right?  If they had different logic how would the computer know which one to execute? Well they actually can as long as the parameters are different.  As long as your methods each differ like this:

then the compiler is able to recognize them each as individual methods.  So now if a user wants to add a contact it doesn’t matter how much information they give!  They can either call addNewContact(Carl, “1112223333”) or addNewContact(“Carl”, 1112223333, “Friends”) and their new contact will be added with that info.

Order counts too, you could have the methods addNewContact(String name, int phoneNumber) and addNewContact(int phoneNumber, String name) as two separate methods in the same class.  This doesn’t open many doors in this specific scenario, but it’s handy to know all the same.

Overriding:

While it sounds almost identical, overriding a method is a somewhat different technique.  This allows us to take a method that exists in a parent class and change its behavior.  As a demonstration let’s say that our contacts app has a page where you can look at individual groups.  When you open the group for “Family” there is a button where you can add contacts to this group.

Our new class named FamilyGroup will extend our NewContact class.  By doing so it now has access to the parent class’ methods.  But we don’t want our user to have to type in the group they are going to use.  That’s a waste of time for them since they’re already in “Family”.  To fix this we’ll override our addNewContact(int phoneNumber, String name) like so:

Now when a user puts in info for a new contact’s name and phone number this method will call NewContact’s addNewContact(int phoneNumber, String name, String group) and pass in “Family” for the group.  Sure, we could have written another function in this class to add the contact, but this way no matter how complicated NewContact’s method is, we get to call it again with only one line of code!

Wrapping up:

Overriding and overloading can make your code a lot neater if used properly, and there’s a tone of cool things you can do with these techniques in the real world.  This contacts app isn’t the most realistic project, but it gets the simple idea across.  When you start getting into more complex inheritance overriding can save you a ton of space.

If you enjoyed this post at all and want to learn more about Android development check out some of our other tutorials such as how to develop augmented reality or more complex apps!

 

Let Firebase Cover the Basics For You

Share if the site was helpful

Let Firebase Cover the Basics For You

When it comes to writing code, the less you have to do the better.  You want control over how your applications behave, but if you can piggy back off of other developer’s work then that’s generally a good thing.  And if you’re hoping to be an app developer, then one of the best tools for piggy backing is Firebase.

Using others to your advantage:

If you think about it even developing the most basic app takes the work of countless others.  Someone else had to develop the programming language you’re writing in, someone else had to build the IDE (probable Android Studio) that you’re developing on, and someone had to…well you get the point.  Any modern-day invention was not created from nothing, it came about thanks to the ground work being done by something that came first.

This doesn’t mean you can’t be innovative.  It means that there’s nothing wrong with using 3rd party libraries and tools to make your development journey easier.  If you don’t have to worry about the basics then you can focus on what makes your app great.  Ok enough justification, let’s talk about how you should use Firebase to make life easier.

Authentication and Data Management:

How many apps do you have that require you to sign in to fully use features?  Of those how many let you create and account through Facebook?  Users hate having to create sign-in info, a decent percentage won’t even go through the process because of the extra 10 seconds it takes.  So including an option for one-click sign in makes it more likely your app will succeed from the start.  Firebase makes this feature easy to leverage allowing you to create a sign in screen with companies like Facebook, Twitter, and Google. 

When users sign up Firebase keeps track of their info and allows user management to be easily configured.  If a user gets a new phone they can log in and Firebase will associate them with the same account.  Firebase also has a database feature allowing you to create and store JSON info, so users can interact with one another and store information easily.  Let’s say you wanted to create that new social media app which lets people post pictures and message one another:  Firebase should be your go to.

Analytics:

When you release an app it’s best to have a game plan for what’s next.  What if users love one part of the app but never use another?  Well if that’s the case then you should aim for a redesign that either brings in new features or directs the users attention to things they are more interested in.  Of course if you release an app and people in other countries start downloading it you can’t exactly track them down and ask them how they’ve been using the app.

This is where analytics come in.  Firebase gives you the capability to monitor user events (anonymously) so you can see which features are getting the most interaction.  If you have a search bar in your app that no one ever clicks on, it’s either time to drop it or move it elsewhere to try again.  Analytics can keep you in know for how your app is behaving and what should change.

Crashlytics:

And on the topic of what should change in app behavior, crashes are about the worst thing a user can experience.  You may be getting 1 star ratings in the app store because your app shuts off randomly for some users and you don’t know why.  Firebase offers Crashlytics to look at the stack trace details for every crashed application.  If there’s one button in your app that is broken and slipped through your checks when publishing, now you’ll be able to see that it’s responsible for the crashes and act accordingly.

Firebase offers a ton of other features that can make development easier and the user experience more fluid.  These are just the tip of the iceberg and features I enjoy using on a daily basis.  If you want to learn how to incorporate Firebase into your apps then checkout Phonlab’s Android Development Course!

 

That Missing Guide To Kotlin Part 2

Share if the site was helpful

That Missing Guide To Kotlin Part 2

In part one of our Kotlin series we began exploring the newly adopted language.  We saw a few examples of how it can make our code more concise and user friendly than Java including type inference and inline constructors.  In part two we’ll continue to show how Kotlin can make your code easier to work with while focusing on one dreaded Java roadblock: The NullPointerException.

If you’ve written anything in Java before then you’re familiar with NPE’s.  It occurs when you attempt to interact with a variable’s value, but it turns out there is no value to interact with.  Your compiler can’t see that there’s no value available, but at run-time your system checks for it and then crashes when it can’t be found.

Kotlin to the rescue

While Kotlin is 100% interoperable with Java (99% really as we’ll see soon) it’s fundamentally different in a few aspects.  One of these is nullability.  In Java every variable has a default value.  This is the value it can fall back on if you never explicity say what value it contained.  For example when you declare a boolean variable, unless you specify its value, it will be false.  For any variable that isn’t a primitive type, the default value will be null.  This can be really useful at times, but it allows us to accidentally try to grab a value when there isn’t one.

In Kotlin its possible to completely avoid this situation. Every variable that is declared is either a nullable type or a non-null type.  What this means is that along with declaring what type of value (Int, Boolean, custom class) your variable holds, you declare whether it is ever allowed to be null or not.  Here are two varaibles declared in Kotlin.  The first can never be null, while the second is nullable.

As you can see, the question mark is used to show a variable has the possibility of being null.  If there’s no question mark in the variables declaration, then you are safe to use it in every situation without risking it throwing an NPE.  This means that you’ll never have to write if statements checking if a variable is null to play things safe. Goodbye useless lines of code

Nullablility In Action

When using non-null type variables, we don’t have to check if there is a value present.  But for other situations we still must take precautions.  One way that Kotlin allows us to do this concisely is through safe calls.  A safe call looks similar to the traditional method of retrieving a value, except we include a question mark at the end of the variable.  So

Becomes

By doing this we can almost read the code as if it’s English.  We’re asking “does the pet exist?”, and if the answer to that question is yes then we move on to the name characteristic of our pet.  If there is no pet that has been created at this point in our code, instead of the app crashing our variable will be given a value of null.

This becomes incredibly powerful when we start chaining safe calls.  Let’s say we want to check if a company has an HR department with an employee name Toby who at tuna for lunch.  Instead of writing a null check for each of these before interacting with them we can write

If along the way any of these things doesn’t exist, then the code will finish the statement returning null and not interacting with any of the variables past the break.  Without an HR department the code won’t crash, but instead our employee variable will be set equal to null.

Control Is A Good Thing

This is probably the most common feature of Kotlin that you see people talk about, and it’s because of how powerful it is.  Not having to deal with null values is amazing, but even when we have to our code can be concise and clean.

The language can also smart cast nullable variables into non-null given the proper verification at first.  So if you had a nullable variable and then explicitly check if it wasn’t null, then you wouldn’t need to use any ?’s moving forward when accessing that variable.

Kotlin isn’t perfect, but when it comes to dealing with null values it has everything that Java has to offer with some additional perks and changes.  We’ll continue exploring some of Kotlin’s advantages in part 3.  In the mean time if you have any questions about how nullability works let us know in the comments below!

en English
X