Android Kotlin Basics – Property Encapsulation

About This Series

This “Android Kotlin Basics” blog series is all about fundamentals. We’ll take a look at the basics of building Android apps with Kotlin from the SUPER basics, to the standard basics, to the not-so-basics. We’ll also be drawing comparisons to how things are done in Kotlin vs. Java and some other programming languages to build Android apps (like C# and Xamarin or JavaScript/TypeScript for Hybrid implementations).

Check Out the Pluralsight Course!

If you like this series, be sure to check out my course on Pluralsight – Building Android Apps with Kotlin: Getting Started where you can learn more while building your own real-world application in Kotlin along the way. You can also join the conversation and test your knowledge throughout the course with learning checks through each module!

Watch it here: https://app.pluralsight.com/library/courses/building-android-apps-kotlin-getting-started/table-of-contents

Kotlin Property Encapsulation

Okay, let’s get to it then. Kotlin is an object-oriented, statically typed, programming language. This means we use interfaces, classes, and abstract classes (among some other unique data structures) to define our data and objects. Encapsulation in our classes serves 2 primary purposes – Code security and architecture strength. It’s how we restrict access to these data structures as well as their contained properties and functions.

In this post we will focus on how we encapsulate properties within our classes, interfaces, and more. Kotlin is 100% interoperable with Java so its practices have to work back and forth with the limitations of Java as well. Let’s take a look at ways we encapsulate properties in Java first, then show how much better it is in Kotlin!

Let’s look at 2 classes – Animal and a child class Dog. We’ll first be showing the Java implementation, then look at how much nicer the Kotlin implementation is!

Animal.java

abstract class Animal {
    // name property
    private String name;

    // constructor with name parameter
    protected Animal(String name) {
        this.name = name; // sets the name
    }

    public String getName() {
        return this.Name
    }
    public void setName(String name) {
         this.name = name;
    }
}

Dog.java

public class Dog extends Animal {
    private String breed;
    // constructor with name parameter
    protected Dog(String name, String breed) {
        super(name); // sets the name through base constructor
        this.breed = breed;
    }

    public String getBreed() {
        return this.breed;
    }

}

To summarize the relationship – Animal has a property called name that we have access to both get and set via the getName and setName functions. Dog then inherits those functions from the Animal class and adds a new property called breed, but breed can only be set by the constructor, so we do not create a setBreed function.

This is just a simple example of encapsulating properties and using functions to manage the access of reading and writing the data separately.

Now let’s see how much better this looks in Kotlin:

Animal.kt

abstract class Animal(public var name: String) { }

Yup… that’s literally it. This creates an abstract class with a public property name that is instantiated in the constructor and has public access to both read and write.

Now let’s look at how that inheritance works and how to restrict write access

Dog.kt

class Dog(name: String, breed: String) : Animal(name) {
    val breed: String = breed
        private set
}

4 lines of code. A class that inherits everything from Animal and has a breed property that is set by the default constructor and can only be set privately.

You can use these get and set modifiers to restrict access to either as well as create custom “dynamic” getters and setters (that we will look at further later in the series).

There are many different ways to handle the code above in Kotlin, but I wanted to demonstrate the shortest and most direct. In future parts of the series, we will also look at constructor overloading, dynamic getters/setters, val vs. var, and so much more.

One last thing – because Kotlin is interoperable with Java, we need to know how this ends up outputting in Java. When we create custom getters and setters for public properties, it actually creates a dynamic function getPropertyName and setPropertyName that can be consumed by Java. And even does it the other way around. If you reference a Java library in your Kotlin code, you can access the underlying property since it will automatically map methods with the prefix of “get” or “set” to custom properties. Pretty cool!

For those coming from a C# background this is extremely similar to how C# handles property getters and setters. In C# it will create methods with the name get_PropertyName and set_PropertyName to handle the dynamic encapsulation and implementations! Kotlin pulls the best parts from the best langauges!

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

 

Advertisements

Pluralsight Course Announcement – Building Android Apps with Kotlin: Getting Started

Today’s the day! My first Pluralsight course Building Android Apps with Kotlin: Getting Started has finally released!
Take a look at the course here: https://app.pluralsight.com/library/courses/building-android-apps-kotlin-getting-started/

And read below for more information.

What’s in it for me?

In this course, we take an introductory look at Android application development with the newest language set out to replace Java – Kotlin. This is a beginner’s course to both Android and Kotlin, so no experience in either is required. If you have some Android knowledge, come take a look at how it looks in Kotlin, and if you have some Kotlin experience, take a look at how it is applied to Android development.

In the end you’ll leave the course with a fully built real-world application that you can always look back to and reference in your own Android apps going forward!

Touch on topics such as:

  • Android fundamentals
  • Activities and their lifecycle
  • Fragments and their lifecycle
  • Creating models in Kotlin to represent remote data
  • Accessing data over HTTP
  • Storing data locally on the device with Sqlite and Anko
  • Making asynchronous data calls to ensure the UI remains smooth
  • Material design
  • Other helpful tools and libraries
  • Comparing Java to Kotlin
  • So much more…

 

I’m planning a paired blog series to tag along with the course that will focus on some other basic Android+Kotlin concepts and draw comparisons to how they were done in Java and how they should be done in Kotlin, so keep an eye out for that as well!

Feedback

Again, this is my first course completed with Pluralsight, so I’m always looking for feedback or questions you might have about the course. You can either, comment in the “Discussion” section of the course, comment on this post, or reach me on Twitter @Suave_Pirate. What did you like? What could have been done better? What are you stuck on?

Thank You!

A special thank you to my Editor, Alex Walton, and my Author Success Manager, Beth Gerard-Hess for their help through the process as well as the rest of the Pluralsight team for being so great while I produced my first course.

 

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.