Xamarin.Controls – Material Form Control Updates

A while back I put together a GitHub repository for Material Design Controls for form elements (Entry, Picker, etc.) for Xamarin.Forms (iOS, Android, and UWP).
You can find some of the original posts about that here:

And you can find the GitHub repo and NuGet package here:

In this post, I wanted to focus on some of the newer features I’ve added to the latest 2018.1.28-pre1 release.

The gist is:

  • Invalid vs. Valid State
  • Font updates
  • Color flexibility

With these, you can now specify updated default colors, invalid state colors, and the original focused accent colors.
Here’s an example of a Style resource that uses these:

    <!-- Material Entry Styles -->
    <Style x:Key="PrimaryMaterialEntry" TargetType="material:MaterialEntry">
        <Setter Property="AccentColor" Value="{DynamicResource PrimaryColor}"/>
        <Setter Property="DefaultColor" Value="Gray"/>
        <Setter Property="InvalidColor" Value="Red"/>
    </Style>

What does validation state mean? You can attach behaviors to easily add validation to your material form controls. Here is an example behavior on the MaterialEntry that requires a length, and sets the state:

   /// <summary>
    /// Material entry length behavior. Allows for the limitation of the text with a min and max length
    /// </summary>
    public class MaterialEntryLengthValidationBehavior : Behavior<MaterialEntry>
    {
        public int MaxLength { get; set; }
        public int MinLength { get; set; } = 0;

        /// <summary>
        /// Attach events on attachment to view
        /// </summary>
        /// <param name="bindable">Bindable.</param>
        protected override void OnAttachedTo(MaterialEntry bindable)
        {
            base.OnAttachedTo(bindable);
            bindable.TextChanged += OnEntryTextChanged;
            bindable.EntryUnfocused += Bindable_EntryUnfocused;
        }

        /// <summary>
        /// Detach events on detaching from view
        /// </summary>
        /// <param name="bindable">Bindable.</param>
        protected override void OnDetachingFrom(MaterialEntry bindable)
        {
            base.OnDetachingFrom(bindable);
            bindable.TextChanged -= OnEntryTextChanged;
            bindable.EntryUnfocused -= Bindable_EntryUnfocused;
        }

        /// <summary>
        /// Stop text input once max is hit
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">E.</param>
        void OnEntryTextChanged(object sender, TextChangedEventArgs e)
        {
            var entry = (Entry)sender;

            if (entry.Text == null)
                return;

            // if Entry text is longer than valid length
            if (entry.Text.Length > this.MaxLength)
            {
                string entryText = entry.Text;

                entryText = entryText.Remove(entryText.Length - 1); // remove last char

                entry.Text = entryText;
            }


        }

        /// <summary>
        /// Set invalid on unfocus if the min is not met
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">E.</param>
        void Bindable_EntryUnfocused(object sender, FocusEventArgs e)
        {
            var entry = (MaterialEntry)sender;
            if (MinLength > 0)
            {
                if (entry.Text == null || entry.Text.Length < this.MinLength)
                {
                    entry.IsValid = false;
                }
                else
                {
                    entry.IsValid = true;
                }
            }
        }
    }

Then you can attach it to a MaterialEntry

<material:MaterialEntry Placeholder="CVV" Keyboard="Numeric" Text="{Binding CVV}" Style="{DynamicResource PrimaryMaterialEntry}">
    <material:MaterialEntry.Behaviors>
        <behaviors:MaterialEntryLengthValidationBehavior MaxLength="3" MinLength="3"/>
    </material:MaterialEntry.Behaviors>
</material:MaterialEntry>

And then you get:
Screen Shot 2018-02-22 at 4.19.52 PMScreen Shot 2018-02-22 at 4.19.57 PMScreen Shot 2018-02-22 at 4.20.03 PMScreen Shot 2018-02-22 at 4.20.11 PM

These validation states, and updated color properties are available on all the Material Forms controls, so install the preview nuget package and get started!

Install-Package MaterialFormControls -Version 2018.1.28-pre1

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 – Auto-mapping Views

About This Series

This “Andorid 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

Auto-mapping Views

We’ve talked in previous posts about how awesome Kotlin is and showed off some of the great features of the language on its own, but did you know Kotlin gets even better when building Android apps?

The Problem

Let’s talk about the obnoxious pattern in Android of having to find a view from the associated layout before using it. I’m talking about this:

// java
Button myButton = (Button)findViewById(R.id.myButton);

If you’re totally new to Android development as a whole, this is what you do in your Activities, Fragments, ViewHolders, etc. to get a reference to a control on your page that was created by a layout resource. This means that if you have a page with many controls and views, you will need to execute the above style code for every single one.

What does this mean?

Your code looks gross. You have massive blocks of properties in your class and an equally massive block of findViewById in your onCreate or other lifecycle method. It also means that you query your View Object far more than you should need to. Other platforms like iOS and UWP (or any other windows app) create outlets or partial properties that hide the creation of the view in your code, but allow you to use it, which means your code stays super clean.

Because of this awful practice in Android, people have come out with some seriously helpful projects (I’m looking at you Butterknife!) and libraries that will automatically handle mapping them to properties in your Activity and Fragment classes like this:

// Java with Butterknife
class ExampleActivity extends Activity {
  @BindView(R.id.title) TextView title;
  @BindView(R.id.subtitle) TextView subtitle;
  @BindView(R.id.footer) TextView footer;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_activity);
    ButterKnife.bind(this);
    // TODO Use fields...
  }
}

That’s a little better, but still a lot of wire up before you can even use the controls in your code.

Kotlin to the Rescue

Kotlin, I cannot thank you enough for doing this…

Kotlin created an Android extension that allows for your Activities to auto-map their layout views by their id in to useable controls!

Here’s how it works: Let’s say you have a layout resource that looks like this:

activity_example.xml

<LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView android:id="@+id/detailTextView"
        android:text="This is a description within a text view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <EditText android:id="@+id/newEntryEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

In your Activity, you simply need to import the extension, and your Activity will automatically have a property it can use that will be pulled from the layout file:

import kotlinx.android.synthetic.main.activity_example.*

class ExampleActivity: Activity() {
    override fun onCreate(savedInstance: Bundle?) {
        setContentView(R.layout.activity_example)
        detailTextView.text = "my new text that was set when auto-mapping"
    }
}

Beyond making the code so much cleaner, this Kotlin Android Plugin also uses built in caching of the views it finds in order to avoid re-querying the View Object since it can be cumbersome and slow.

For more details on how to customize this behavior, and use the extension more in depth, check out Kotlin’s documentation on it here: https://kotlinlang.org/docs/tutorials/android-plugin.html

Also, let me know what else you’d like to learn about with Android and Kotlin! Either drop a comment here or tweet at me @Suave_Pirate!

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 – Lambdas and Higher Order Functions

About This Series

This “Andorid 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.

Android Kotlin Basics – Null Safety and Coalescing

About This Series

This “Andorid 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 “Andorid 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 = &quot;Bark&quot;
    var name: String? = null // set this later

    fun speak() : String {
        // throw an error if name is null
        val log = name!! + &quot; said &quot; + 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 “Andorid 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 “Andorid 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.