Android Kotlin Basics – Lambdas and Higher Order Functions

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

Lambdas and Higher Order Functions

Lambdas and Higher Order Functions are a great tool to use in development to pass logic around between different blocks in our code. This allows us to pass functions into other functions and execute them when we need to, and there are a few different ways to do this, but let’s start with Higher Order Functions in general.

Higher Order Functions

Higher order functions are ones that consume another function as a parameter. This means the higher order function can execute the inner function any number of times. This is commonly used for wrapping function calls, manipulating collections with the given function, or executing a callback function. Here’s an example of what that looks like with a callback function:

fun makeHttpGetRequest(string url, callback: (data: String) -> String) {
    url.httpGet() // using Fuel library as an example
       .responseString { request, response, result ->
      //do something with response
      when (result) {
          is Result.Failure -> {
              error = result.getAs()
              callback(error) // executing the passed in function
          }
          is Result.Success -> {
              data = result.getAs()
              callback(error) // executing the passed in function
          }
    }
}

In this example, we created a wrapper function for making an HTTP GET request that executes the callback function with either the error string or data as a string. Even more, we use another higher order function from the Fuel library responseString that takes in a Triple or a lambda/function with three parameters.

We define our inner function like so:

(<parameters>) -> <return type>

If your inner function does not have a return type, you simply set the return type as the Kotlin Unit – the equivalent of void. If you’re coming from F#, that will look familiar. That means a lambda with no parameters and no return type would be:

() -> Unit

Ways to Use Lambdas and Higher Order Functions

Basically, there are a few different ways you can define a function and pass that in as the parameter of the higher order function.
You could:

  • Define the function ahead of time and pass the definition in
  • Construct a Lambda Expression or Anonymous Function when invoking the higher order function

Let’s look at the first example of predefining a function to pass in. Let’s use the higher order function map that is an extension function on a List:

fun <T, R> List<T>.map(transform: (T) -> R): List<R> {
    val result = arrayListOf<R>()
    for (item in this)
        result.add(transform(item))
    return result
}

This method takes in a transform function to handle how to map the initial List of type T to a new List of type R, and the higher order function uses the transform function to execute against each item in the original list.
If you’re coming from C#, this is like the .Select() LINQ extension method.

Let’s now define our transform method we want to use and pass it in to a map call:

// define some simple classes
class Dog (val breed: String) { }
class Pet(val petType: String, val breed: String){ }

fun createPetFromDog(dog: Dog) : Pet {
    return Pet("dog", dog.breed)
}

var dogs = List<Dog>()
// fill with dogs

var pets = dogs.map(::createPetFromDog);

We use the :: prefix to inform the compiler that this is an existing function or other member.

Now let’s look at creating this same scenario, but using lambda expressions instead. There are even a few ways we can do this too!

// define some simple classes
class Dog (val breed: String) { }
class Pet(val petType: String, val breed: String){ }

var dogs = List<Dog>()
// fill with dogs

// define the transform function as an explicit lambda
var pets1 = dogs.map({dog -> Pet("dog", dog.breed));

// define the transform function, but outside the actual parameters
// this is a shortcut provided by Kotlin to help with readability
// note that the "()" after the map is not required when defining it this way
var pets2 = dogs.map(){ dog ->
    return Pet("dog", dog.breed) // note the return here is not technically required
}

// use the "it" keyword since we only have one parameter.
// the "it" keyword is another shortcut provided by Kotlin
// for lambdas with only 1 parameter
var pets3 = dogs.map { Pet("dog", it.breed) }

Notice how many different ways we can execute the exact same thing in the end. We see this in many places with Kotlin, and it gives us as developers the freedom to define a bit of our own style in the code of our projects, or to use different strategies at different times to help with readability.

Now get out there and start using nested functions!

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.

Advertisement

Android Kotlin Basics – Null Safety and Coalescing

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 Null Safety

The NullReferenceException and NullPointerException… The bane of many of our lives as developers… say “goodbye” in Kotlin!

Kotlin made the early decision to alleviate the pain of null checks in our code.
In Kotlin, your properties, return types, local variables or values, and everything else needs to be explicitly nullable – not just primitive types, but complex types like your own classes and interfaces too!

Here’s what I mean:

class Dog() {
    val name: String 
    // this won't compile! name is NOT a nullable string, 
    // so it MUST be initialized!
}

...

class Dog() {
    val name: String = null
    // this won't compile! name is NOT a nullable string, 
    // so it MUST be initialized with a non-null value!
}

...

class Dog() {
    val name: String? = null
    // This works! name is a nullable string and is initialized with
    // null
}

...

class Dog() {
    val name: String = "a name"
    // This works because the type is a non-nullable string 
    // and is initialized with a string literal
}

Okay, so now we know that variables and values must be initialized with either an explicit nullable type or a non-nullable value, but what about if we have a nullable type, and try to do something with it? Let’s take a look!

val dog: Dog? = null

println(dog.name) 
// This won't compile! dog is a nullable type, so you need
// access the name property either dangerously or safely with
// null coalescing

...

val dog: Dog? = null
println(dog?.name) // This works! it will print null
println(dog!!.name) // This will compile, but throw an exception!
println(dog?.name?: "a default name") // this works! it will print "a default name"

Kotlin takes null coalescing to the next level by allowing you to provide a default value if anywhere along the chain is null. This is what we do in the above example – this means that if dog or dog.name is null, we use the default provided value notated with the ?: notation.

This also works for invoking functions with null safety!

class Dog() {
    fun bark() {
        println("WOOF!")
    }
}

...

val dog: Dog? = null
dog?.bark() // this works! but nothing will happen since dog is null

...

val dog: Dog? = Dog()
dog?.bark() // this works and prints WOOF!

Those are the basics of handling your nulls in Kotlin! No more ugly code like this:

if(dog != null && dog.name != null) {
    println(dog.name);
}

Shorter – Simpler – Easier to read and follow. Once again, using Kotlin makes our lives so much easier while building our apps.

Coming up in future posts, we’ll start looking outside just the basics of the language, and start implementing them with Android common situations!

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.

Android Kotlin Basics – “val” and “var”

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 “val” and “var”

This one is pretty simple, especially for those coming from Java, but seeing the left side of the argument when creating either a property or local variable as “val” or “var” can be pretty weird.

Here’s what I’m talking about – let’s create a class that has two properties, one that is a value and one that is a variable (see what I did there?).

class Dog() {
    val bark: String = "Bark"
    var name: String? = null // set this later

    fun speak() : String {
        // throw an error if name is null
        val log = name!! + " said " + bark
        prntln(log)
        return log
    }
}

The quick answer is that val – being a “value” can only be set once. This is just like using the final keyword in Java. var on the other hand is a “variable” and can be set later on or can have it’s value changed whenever.

Using val in your properties makes it readonly. If you’re coming from C#, it’s like adding the readonly keyword to your class’s property, since it is a val and properties need to have a value set during the init or constructor of the class. We’ll talk more about class initialization and constructors in another post of this series.

By using val and var in the Kotlin language, it allows us to always have our properties and local variables aligned vertically which makes the readability of our code that little bit better!

In the next post, we’ll look at how Kotlin handles null references and helps us write safer code and get rid of the dreaded NullPointerException or NullReferenceException!

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.

Android Kotlin Basics – Extension Functions and Properties

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 Extension Functions and Properties

If you’ve come from a C# background this introduction to Kotlin extensions will feel like home.

Kotlin extensions allow for us developers to extend the functionality of a given type, whether it be a class, interface, or object. These extensions are resolved statically meaning that they are essentially added as static functions and members of the given type that is being extended.

It’s important to note that Java does not have a way to build extension methods, so in this case, we won’t be able to compare how it is done in Kotlin and Java since this is only possible in Kotlin. However, it IS possible to use Kotlin extension methods in your Java code that is referencing it.

Extension Functions

Let’s take a look at what an extension function looks like. Let’s first define a simple class Dog, and then we will add extensions to it.

Dog.kt

class Dog {
    var name: String = ""
    var breed: String = ""
}

DogExtensions.kt

fun Dog.printNameAndBreed() {
    println(this.name + " " + this.breed)
}

Now in our consumer code, we can use it like so:

MainActivty.kt

class MainActivity: Activity() {
    override fun onCreate(savedInstance: Bundle?) {
        val dog = Dog()
        dog.printNameAndBreed()
    }
}

Note the use of the keyword this within our extension method. this refers to the instance of the class that the extension method is being invoked in. However, this is not required unless you have naming conflicts with other local variables. So it could also be written as:

DogExtensions.kt

fun Dog.printNameAndBreed() {
    println(name + " " + breed)
}

This allows for a shorter syntax for writing the extension. Compare that to a C# extension method:

DogExtensions.cs

public static class DogExtensions
{
    public static void PrintNameAndBreed(this Dog dog)
    {
        Console.WriteLine($"{dog.Name} {dog.Breed}");
    }
}

Skipping the need for the parameter for the extension type allows for the signature of the signature to be the same as when it is invoked, which C# does not do.

Extension Properties

Just like extension methods, Kotlin supports creating extension properties. However, these extension properties cannot contain intializers like we use when initializing our properties on a class. Extension properties do not create an actual member of the class and thus need explicit “getters” and “setters” on the property (or just one or the other if you want to restrict it). Let’s see a quick example using our existing Dog class:

DogExtensions.kt

val Dog.nameAndBreed : String
    get() = this.name + " " + this.breed
    set(value: String) { 
        var nameAndBreedArray = value.split(" ")
        name = nameAndBreedArray[0]
        breed = nameAndBreedArray[1]
        // note the absence of the "this" keyword since it is optional
    }

Notice, that we cannot have to explicitly define get() and set() within our nameAndBreed extension property. Then within these, we access the fields on the class.

If we try to instantiate an extension property with an initializer, we will get a compile-time error. For example, this is not allowed:

val Dog.nameAndBreed : String = "Ryder Labrador" // <- not allowed!

Extensions with Nullables and “Any” Types

With Kotlin extensions, you can also add nullable types:

fun Dog?.printNameAndBreed() {
    if (this == null) return; // just return out if it is null
    println(name + " " +breed)
}

This means you can also use it with the Any type in Kotlin:

fun Any?.print() {
    if(this == null) return;

    // now print out the string version of the object
    println(toString()) 
}

We’ll get a little more into the Any type in another post of this series, but the short version is that it is a valid Kotlin type that is not restrained to an actual pre-existing or new type. This works the same way as the TypeScript any and is most useful in functional programming when using type inference more.

That’s about it for Kotlin extensions! Extensions are great – they allow for separating some concerns and keep your actual model class definitions short and clean and put some other logic around it in a restrained location. Or to help extend the functionality of a third party library that you don’t control. All in all, it was a great design decision that the Kotlin team made to make building our applications even cleaner and easier!

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.

Android Kotlin Basics – Package Level Functions and Members

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 Package Level Functions and Members

So, Kotlin is an object-oriented language, however, it is not exclusively an object-oriented language. What does that mean? You can actually use Kotlin in a completely functional way and not require any of your implementation to be encapsulated within interfaces and classes. In Kotlin, you can define code within functions and property/variable members from the package level! This may be a weird concept for those coming from an exclusively object-oriented background, and especially from Java, but luckily, Kotlin simplifies so much of this confusion and makes it really simple to use back and forth.

In the last Android Kotlin Basics, we looked at static classes and functions, but Kotlin actually suggests using package level functions rather than companion objects or regular objects when needing simple static methods.

How does this work? Well, the name sort of speaks for itself! These are functions and members within a Kotlin file, but not class. Then they belong to whatever package you declare the file belongs to, OR, to the entire root package if you don’t specify one at all.

Here’s what that looks like:

HelperFunctions.kt

package com.suavepirate.helpers
// this is a file with random functions that belong to the package above.

fun sayMyName() {
    println("Alex Dunn - Suave Pirate")
}

fun isThisTrue(trueOrFalse: String){
    return trueOrFalse == "true" ? true : false
}

val bestLanguageForAndroid: String = "Kotlin"

Now we can use these functions in three different ways:

  1. Import each function / member
  2. Import package with wildcard
  3. Reference each call with the package name

MainActivity.kt

import com.suavepirate.helpers.sayMyName
import com.suavepirate.helpers.isThisTrue
import com.suavepirate.helpers.bestLanguageForAndroid
//... other packages

// showing how to use these functions and members with the import
class MainActivity : Activity() {
    override fun onCreate(savedInstance: Bundle) {
        sayMyName()
        val isTrue = isThisTrue("true")
        toolbar.title = bestLangaugeForAndroid
    }
}

With the wildcard import:

MainActivity.kt

import com.suavepirate.helpers.*
//... other packages

// showing how to use these functions and members with the import
class MainActivity : Activity() {
    override fun onCreate(savedInstance: Bundle) {
        sayMyName()
        val isTrue = isThisTrue("true")
        toolbar.title = bestLangaugeForAndroid
    }
}

Or without using the package import:

MainActivity.kt

//... other packages, but not the one where the members live

// showing how to use these functions and members without the import
class MainActivity : Activity() {
    override fun onCreate(savedInstance: Bundle) {
        com.suavepirate.helpers.sayMyName()
        val isTrue = com.suavepirate.helpers.isThisTrue("true")
        toolbar.title = com.suavepirate.helpers.bestLangaugeForAndroid
    }
}

This allows us to use these members and functions in either a static way, or in a functional way if your entire application wanted to focus more on that pattern over object-oriented! Kotlin gives us so many options!

But what about using this pattern when mixing Kotlin and Java? Underneath the hood, the Kotlin compiler will actually create a class for the entire package that wraps all of the members and functions within it. This means that in Java, we can use it in the exact same way! It then uses the naming convention of {PackageFinalName}Package

MainActivity.java

import com.suavepirate.helpers;
//... other packages

// showing how to use these functions and members with the import
public class MainActivity : Activity() {
    @Override
    void onCreate(Bundle savedInstance) {
        HelpersPackage.sayMyName();
        Boolean isTrue = HelpersPackage.isThisTrue("true");
        toolbar.setTitle(HelpersPackage.bestLangaugeForAndroid);
    }
}

Jetbrains themselves have a great post on some greater detail about how this works: https://blog.jetbrains.com/kotlin/2015/06/improving-java-interop-top-level-functions-and-properties/

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.

Android Kotlin Basics – Static Classes and Functions

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 Static Classes

 
Using statics in object oriented design is not really a necessity, but something we find ourselves doing from time to time. This is especially true with newer trends that bring more functional style programming mixed with object-oriented. The first thing to note, is that Kotlin does not define entire static class as “static classes”. Instead, we use what is called an object declaration. It is also true that Kotlin does not use the static keyword at all. Even if you wanted a single static function/method in a non-static class, you need to create what is called a companion object within your class.

Let’s look at example of using statics to implement the Factory Pattern – which allows for an object to create the instance of itself in a lazy fashion, using static methods. To do this in Java, we would create a class and a static function that returns an instance of itself. Here’s an example of doing this in Java and in Kotlin

Dog.java

class Dog {
    public static Dog create() {
        return new Dog();
    }
}

Dog.kt

class Dog() {
    companion object Factory {
        fun create(): Dog = Dog()
    }
}

There are a few differences that happen when using these companion objects from our Kotlin classes within our Java code.
When creating a companion object, it creates an inner class with a static method on it in Java, so to invoke the above factory create function, you would call

Dog.Factory.create();

but in Kotlin, you can simple say

Dog.create()

Also, the name of the companion object is optional, so you could simply say:
Dog.kt

class Dog() {
    companion object {
        fun create(): Dog = Dog()
    }
}

But to call this in Java, you would say:

Dog.Companion.create();

If you REALLY don’t want to have to call the .Companion from your Java code, you can use the @JvmStatic tag like so:

class Dog() {
    companion object {
        @JvmStatic
        fun create(): Dog = Dog()
    }
}

Then you can use it in Java the same way you do in Kotlin:

Dog.create();

On the same note as using the companion object, you can also create regular object declarations at the package level, and use functions within those in a static manner:

// remember, Dog factories in real life 
// are awful, awful things, but in the context of Data
// they are okay.
object DogFactory {
    fun create(): Dog = Dog() 
}

And this can be called directly if the package is imported:

DogFactory.create()

Next Steps

Although this is the best solution for creating static classes and methods the same way Java does it, the standards of Kotlin actually suggest using a completely new pattern – package level functions. We’ll talk about that in the next post of the series!

Statics are also extremely useful for another feature that helps Kotlin stand out – Extension Functions and Properties. These are very similar to C# extension methods, but with even more features. We will also cover this subject in a later post.

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.

Android Kotlin Basics – Visibility Modifiers

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 Visibility Modifiers

Visibility modifiers are what we use to facilitate the Encapsulation and Polymorphism aspects of object-oriented design and it seems that every language handles a few things differently. We use modifiers to restrict access to certain parts of our code from other code. We know Kotlin is interoperable with Java, but their visibility modifiers are actually different in a few ways!

Java has 4 primary modifiers:

  • public
  • private
  • protected
  • package-private: The default if you do not explicitly provide one

However, these modifiers are not available for top level structures such as classes or interfaces. All the modifiers are used for members of those classes and interfaces, but only public and package-private are used for the actual classes and interfaces.

Oracle has created a useful chart on what each modifier is and what it restricts:

Access Levels
Modifier Class Package Subclass World
public Yes Yes Yes Yes
protected Yes Yes Yes No
no modifier Yes Yes No No
private Yes No No No

source: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

Those are pretty straightforward. public means everyone gets to see it, protected means subclasses and packages can see it, package-private means objects in the same package see it, but that’s it, and private means only the immediate class can see it.

Let’s look at Kotlin’s implementation, and what I personally believe to be more useful and logical. If you come from a C# background these will seem familiar.

Kotlin has 4:

  • public
  • private
  • protected
  • internal

One important thing to note is that Kotlin, unlike many other languages, defaults to public. This means everything is exposed, and it is up to the developer to determine what should be hidden. Java’s approach is to enforce the security more directly with their default which then forces the developer to determine what should be exposed. It’s an interesting approach, but the more you get into Kotlin development, the more you’ll see why it is appropriate for the style. Kotlin is statically-typed object oriented, but does not require your code to be written in forced structures, and has a lot of functional aspects to it, but we’ll get into that later in the series.

Let’s create our own chart for these:

Access Levels
Modifier Class Package Subclass World Module*
public or no modifier Yes Yes Yes Yes Yes
protected Yes No Yes No No
internal Yes Yes Yes if in Module No Yes
private Yes No No No No

*Modules are unique to Kotlin and include all files compiled in one source-set. More info here https://kotlinlang.org/docs/reference/visibility-modifiers.html#modules

Some important things to note:

  • protected is not visible to the entire package – it is basically private but also exposes to sublcasses. This is the same as C# protected.
  • internal is like public if the referencing code is within the same Module
  • private is not just for classes, since Kotlin does not actually require a class for functions. private restricts to the actual FILE that the code lives in.

 

Now that we know how to use encapsulation and visibility modifiers, we can start to understand more of how we can secure our code and architect our solutions in strong and logical ways.

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.

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.

 

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.

 

Android – Comparing Models in Kotlin, Java, and C# for Xamarin

Models are an obvious important part of our applications we develop. It’s how we define our data and because of that, we can grow our models to be quite large in number. This post will look at comparing the definition of models between Java, C# (for Xamarin), and Kotlin.

Our example model will be a simple Person that has a Name and Description along with an ID. Let’s look at how we can define our Person model with these fields as well as the ability to access these fields publicly.

Using Java

Java is going to be our largest and most annoying to develop. We need to define our class, private fields, and then public functions/methods to get and set the value of each of the fields. We also need to be able to instantiate a Person with all these properties set in the constructor.

Person.java

public class Person{
    private int id;
    private String name;
    private String description;

    public Person(int id, string name, string description){
        this.id = id;
        this.name = name;
        this.description = description;
    }

    public void setID(int id){
        this.id = id;
    }
    public int getID(){
        return this.id;
    }
    public void setName(String name){
        this.name = name;
    }
    public String getName(){
        return this.name;
    }
    public void setDescription(String description){
        this.description = description;
    }
    public String getDescription(){
        return this.description;
    }
}

That’s exhausting…

Now we can instantiate it and update properties like this:

...
Person bob = new Person(1, "Bob", "He writes code and stuff");
bob.setDescription("He doesn't actually write code");
...

Using C# for Xamarin Applications

C# makes our lives a lot easier with the get and set mechanism built into properties.

Person.cs

public class Person
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    public Person(int id, string name, string description)
    {
        ID = id;
        Name = name;
        Description = description;
    }
}

Nice and neat!

Now we can instantiate it and update properties like this:

...
var bob = new Person(1, "Bob", "He writes code and stuff");
bob.Description = "He doesn't actually write code";
...

Using Kotlin

Kotlin has some cool tricks that allow us to define and set properties directly in our constructor without having to define and set them separately. This gives us the quickest way to create simple POCO definitions and speed up that development time.

Person.kt

class Person(var id: Int, var name: String, var description: String);

One line.

Now we can instantiate it and update properties like this:

...
val bob = Person(1, "Bob", "He writes code and stuff");
bob.description = "He doesn't actually write code";
...

Conclusion

Each language has their nuances, but I think we can all agree that defining models in Java is just a headache that other languages have solved with better solutions.

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.