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.

Advertisements

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.