What Are Higher Order Functions and Receiver Types in Kotlin?

If you have been programming Java, especially within Android, for a long time, you would know that higher order functions are not really a thing. They are, in such a way that you can pass around a functional interface, however those are not true functions (a function literal to be specific). Fear not, because Kotlin is here and allows you to do just that. A basic higher order function Kotlin allows us to define a function which takes a function (a literal) as a parameter. The syntax for this looks like the following:

We’ve written an empty function which takes a function as a parameter (simply named function  in our case) and does nothing. You should notice that we wrap our argument types in brackets, if we wanted multiple parameters, we’d use a comma to separate them. Right now, this function isn’t doing anything. Let’s change that.

From our main  method, we are now passing a lambda function to functionTest() . We can see that it takes value s  and returns s.plus("!") . All this lambda is doing, is just taking a String and returning the same String appended by a “!”. A little more complex… Higher order functions can grow to be more complex. Let’s see an example where we take a function with multiple parameters on top of having multiple statements in the return clause.

If you’re new to Kotlin, this can look a little confusing. Especially the last line of our main  method. For starters, the last line of our return clause is what is returned. We do not have to include the return  keyword for this – it can be omitted. So, we’re allowed to have an unlimited number of statements, as long as the last line is what is to be returned (a String in this case). Also, as previously stated, we separate …

Playing Sounds with SoundPool in Android

Like MediaPlayer, SoundPool can also be used to play audio files. However, unlike MediaPlayer, SoundPool is more suited for quick sound effects as opposed to longer audio files which require streaming. Before we even begin, we’ll need some sounds to work with (preferably ones with a creative commons license, or similar). You can use google for this or if you’re lazy, http://www.wavsource.com/sfx/sfx.htm.   Storing our sounds Download any number of sounds you like. In your project, create a new folder under app called assets (do not store your sound files in the res folder). You can achieve this by right clicking on app, New -> Folder -> Assets folder. Your project structure should look like the following afterwards, Once you’ve created your assets folder, create another folder within assets. You can name this folder anything you want – we’ll use it for storing our sound files.   Accessing our sound assets To take steps to make our code clean, we will be making a class dedicated to loading and playing our sounds outside of our Activities and Fragments. We’ll start with building that class now. Create a class called SoundPlayer. We’ll need a few methods which will be used to hide away the logic of accessing and loading our sound files from outside classes. Here’s my implementation of SoundPlayer. You can change/add some code to suit your needs but this is the basic gist.

The core components of this class consist of: List  for storing our Sound  objects AssetManager  for accessing our app’s asset files. SoundPool  for playing our sound files. You will also notice two different constants, SOUND_FOLDER and MAX_SOUNDS. They specify the name of the folder we’re storing our sounds and the maximum amount of sounds we allow our SoundPool to play at once, respectively. fetchSounds() is executed as soon as our class is instantiated. It first tries to locate …

Annotations in Java

Annotations in Java, we have all seen and used them in our code. Such examples are @Deprecated , @Override , @SuppressWarnings , @NonNull , @Nullable , etc. Most of us can say what these annotations imply or do, but how do they actually work? Before we discuss them in depth, let’s first understand what their purpose is. What Are Annotations? Annotations are simply metadata that we tie with our code. Meaning, extra data on top of the code we’re already writing. This metadata will be used either during compile or run time. There are three that Java includes, and they are: @Deprecated , @Override ,  @SuppressWarnings . Android also has its own large list of annotations on top of the three included in Java. You can find them here. Annotations In Practice Let’s take a quick look at one of the most common annotations every Java developer comes across: @Override . We’ll use the following Animal  class as an example.

Almost all popular IDEs of have a way of automatically providing override methods. This is done as long as the class we are extending provides no implementation for said method ( makeNoise()  is abstract ). Furthermore, the  @Override annotation is provided above makeNoise()  as well. Its purpose is to state that this class is overriding a parent method. If we were to annotate a method with @Override  that wasn’t a parent method, our IDE would show us an error similar to the one seen in the image below.  The compiler would also throw an error if we tried to build this.   How does it really work? Now you’re probably asking yourself how @Override  is able to tell both the compiler and our IDE that this is in fact an error. Let’s take a look at the code.

Surprised right? The thing with annotations is that they contain no logic. There is nothing in this …

Lambdas in Java

Lambdas in Java can be a little complex to understand at first, but I promise you, they aren’t! In fact, lambdas allow us to write our programs faster, with fewer bugs along with ending up with cleaner code. They also allow for functional programming, however this article will not be diving in to the ins and outs of functional programming in Java – only a basic overview of what lambdas are and how we write them. Before Lambdas… Before we even start talking about what lambdas are, let’s take a step back and look at the basic structure of a method.

This is pretty basic right? Well, try to think of what a method really is in Java. A block of code – steps that are executed sequentially. On top of this, we write this method in a class. The methods we write in that class are actions which that class can perform. The methods are a part of the class. However, what if we wanted to pass this behavior around? Before Java 8, we would do something like the following:

This is basic OOP in a nutshell. If we wanted to create a new behavior (implementation), all we would need to do is create a new class which implements the  PrintText interface, create a new instance of it and pass it to our  printSomething() method. Still, what we’re passing in to printSomething()  is an object which implements our behavior. Now, what if wanted this behavior in isolation? Without having to create a new class implementing our interface? What if we were able to assign this code to a variable, in the same way we define other objects or primitives? Introducing Lambdas What we want to achieve with lambdas is something like the following: Note: the syntax for this section is for example purposes …

Understanding the Activity Back Stack

Knowing how the Activity back stack works will help you to better understand how your activities are managed in the background. As the name implies, the Activity back stack organizes your Activities in a linear stack structure, based on the order in which each is started. Imagine we have an app used for scrolling through and viewing text messages. Each time you tap on a message in the list, a new Activity for reading the full contents of the text is instantiated. Doing this puts our new “message viewing” Activity on top of the stack. Pressing the back button will remove (pop) the Activity from the stack, destroying it in the process, and present the user with the previous list Activity. Activities in the stack are only ever pushed and popped, never rearranged. This is the basic gist of the Activity back stack. When the user starts a new Activity, it is pushed on to the top of the stack and resumed (onResume). The previous Activity is stopped (onStop).  Once the back button is pressed, it is popped off, returning the user to the previous Activity. A basic diagram showing how the stack looks before and after can be seen below                                                       What about tasks? There is also the concept of a task, which is basically a collection of activities committed to one app (or job). These activities are then organized in the back stack. The encapsulation can be seen as follows : Task –> Back stack –> Activities (a task contains Activities which are stored in the back stack) Launch Modes & Intent Flags Not all Activities behave the same way when they are launched. By default, a newly started Activity is always put on top of the stack while the previous is pushed down. This even holds true for …