Kotlin RecyclerView

In this post we will write in Kotlin a very simple example for RecylcerView.

First, you can search for RecyclerView in the view search box. Drag and drop the RecyclerView below ConstraintLayout and you will be prompt to import in app – build.gradle.

activity_main.xml

list_item.xml

 

MyCustomAdapter.kt

 

MainActivity.kt

 

Kotlin ListView with ViewHolder

In this post we will create a ListView with ViewHolder adapter but we will write the code in Kotlin.

For creating xml files for ListView and list items, follow the steps from this post.

Next, you have to create a new Kotlin class for the adapter. Name the new created file MyCustomAdapter

MyCustomAdapter.kt

What’s different in this adapter written in Kotlin compared to the one in Java is that we had to create rowView variable in order to be able to inflate the list_item layout to the view. In Kotlin if we try to inflate the layout directly to the view: View? attribute we will get an error “Val cannot be reassigned”.

MainActivity.kt

 

 

Kotlin Common Questions

1. Where should we keep constants in Kotlin?

  • if you need constants to be accessed globally use const as top-level properties (not inside a class).

In order to do this create a Kotlin file named Constants.kt. The file would look like this:

This way you will be able to access the constants from anywhere within the app just by typing the constant name (in Kotlin code). In Java code you will need to write ConstantsKt.MY_APP_ID.

  • if you have constants that are specific to a scope, like Employee for example, create a companion object

And this is how you use the constants.

2. What do ?, ?., ?: and !! mean?

3. How to make casts in Kotlin?

4. How to use Parcelable in Kotlin?

5. How to create a Singleton in Kotlin?

6. How to create a List in Kotlin?

List

List

  • Create a List in Kotlin

Important!

In Kotlin, lists are immutable by default (you can’t add or remove elements after the list is created). If you need to make a list mutable, you can do this by using mutableListOf

OR

by creating an ArrayList.

BUT it should be just a temporary list. It is not recommended to keep mutable lists for too long.

  • Mixed types

When you create a list in Kotlin, you can add mixed types to the same list:

  • listOfNotNull() Function

The output of the above code will be this:

Notice that null values are ignored.

  • Empty lists

There are 2 ways to create empty lists. They do the same thing, so it’s up to you which way you prefer.

OR

emptyList<String>() returns an Immutable empty list.

7. How to create a SET in Kotlin?

  • Create a Set in Kotlin

  • Create a HashSet

  • Create a SortedSet (TreeSet in Java)

  • Create a LinkedSet (LinkedHashSet in Java)

 

8. How to create a Map in Kotlin?

  • Create a Map

  •  How to iterate a Map?

HashMap, LinkedMap (LinkedHashMap in Java) and SortedMap are all mutable.

9. What collection methods are useful?

any()

Returns true if collection has at least one element.

any(predicate: (T) -> Boolean

Returns true if at least one element matches the given predicate.

 

asReversed()

Returns a reversed read-only view of the original List.

Output

 

Kotlin – for, while, if, when

Control flow: for, while, if, when

This post is for beginners who want to start learning Kotlin language and already know Java. We will show simple examples of for, while, if, when in both languages, in parallel, for an easier understanding. We will use Log.e in order to print string messages, as from our point of view, is easier to read them in the Logcat.

1. for loop

Enhanced For-Loop

Java

  • inline

  • using block

Kotlin

  • inline

Notice that in Kotlin we used a “$” symbol in order to obtain the value of name variable. This is called a template expression.

  • using block

Index-based loop

Java

Kotlin

Notice that here, we used beside “$” symbol, curly braces “{“. This was necessary because names[i] is an expression.

withIndex or Ranges loop

Java

Kotlin

OR using Ranges (Kotlin)

 

2. while loop

The while loop in Kotlin is the same as the while loop in Java.

Both Java and Kotlin

 

3. if expression

Traditional usage

Java

Kotlin

As an expression (inline if)

Java

Kotlin

In both Java and Kotlin, if we use inline if, the “else” branch is required.

As an expression with blocks

Java 

NONE

Kotlin

  • 1 statement

The output for the above code will be:

  • 2 statements or more

The output of the above code is this:

What happens in this case? Well, a is indeed lower than b, so the code from the if branch will be executed. First, it will log the “a is min” message, and then a value will be assigned to “message” variable and the latest Log.e will log the message “min = 1” because a = 1.

As the official documentation states: ” if branches can be blocks, and the last expression is the value of a block”.

4. when expression

when expression in Kotlin is the equivalent of switch in Java.

General form

Java

Kotlin

The output is:

Many cases that should be handled in the same way

Java

Kotlin

The output is:

Arbitrary expressions (not only constants)

Java

In Java we can’t use arbitrary expressions. Constant expressions are required.

Kotlin

Check a value for being in or !in a range or a collection

Java

NONE

Kotlin

The output is this:

 

Check that a value is or !is of a particular type

Java

NONE

Kotlin

Output is:

Notice that in this scenario we assigned the value of when expression directly to the isInt function (method). This is one of the shorter ways of writing a function.

Replacement for an ifelse if chain

Java

NONE

Kotlin

The output is:

Note that in this scenario, when expression is followed directly by a curly brace “{“.

 

 

Kotlin – How to pass function as parameter

Recently, I’ve noticed that there are a few different ways to pass a function as parameter. In this post I will use 2 functions: sum and divide. We have to declare the sum function, in such way that it can receive the divide function as argument.

The most common and often more convenient (according to Kotlin documentation) is to pass a lambda expression.

1. Pass a lambda expression

In order to make the sum function to accept a function passed as lambda expression, we have to declare the 3rd parameter c as a lambda.

  • lambda expression with no parameters

  • lambda expression with 2 parameters

  • pass lambda expression directly without divide method

 

2. Use :: operator

As you can see, the signature for the 3rd param from sum function also changed. As we do not pass a function as lambda, we declare the c parameter as a “normal” Int.

Also, notice how we had to reference the divide function in this case. We had to specify the context (the class in which the function was declared), and the arguments were declared separately inside other parenthesis.

Specifying the context was necessary because the functions are declared in a class. Only if we write the functions directly in a Kotlin file (NOT inside a class) we can call directly ::divide. See the example below:

Functions in Kotlin

In this post I will talk about 5 cool things that functions can do in Kotlin, better than methods in Java.

  1. Forget about overloaded methods

In Java, when you need the same method to have 1 parameter in one case and more parameters in another case, you would have to overload the method. This means to write another method with the same name, but different parameters. In Kotlin, this is history. You can provide default values for parameters, which are used when you do not provide all the corresponding arguments.

  • Java

    Kotlin

     

2. A function can have as a parameter another function

A function that takes another function as parameter is called Higher-Order function.

3. We can create a function inside another function

A function that is created inside another function is called local function.

4. We can create functions without name

A function that does NOT have a name, is called an anonymous function

5. We can use lambdas

A lambda function is a simpler way of representing an anonymous function.

 

Anonymous Functions and Lambdas – Kotlin

Note! This is a post for beginners in Kotlin language.

What are lambdas and anonymous functions? In order to define them let’s see what is a function literal.

Function literal

Function literal is a function that was not declared, but was passed as an expression.

What functions are ‘function literal’?

The following are called ‘function literal’:

  • lambda expressions
  • anonymous functions

Lambda Expressions

Full syntax:

Pass lambda as a parameter to a function with more parameters

NOTE: The equivalent syntax for sum function is:

Let’s do some analysis on this function. It requires the first 2 parameters to be of type int, and the last one as a lambda expression. The lambda expression requires 2 parameters of type int (a, b) and returns an int.

So far, so good. The sum function must return an int also, so when we return lambda (c(a,b)) we actually return an int value in the end.

Also, as you can see, when we want to return a lambda we have to use parentheses with parameters, when they exist. When there is no parameter, then we write only empty parentheses.

Pass lambda to a function that has only the lambda function as parameter

Also the equivalent syntax for one function is:

Overview

  • lambdas are always surrounded by curly braces ‘{}’
  • parameters are defined before “->” symbol
  • the body (what your method should return) is defined after “->” symbol
  • if a function has:
  • more parameters and the last parameter of a function is a lambda expression, then the lambda expression can go outside the parentheses
  • only one parameter and the last parameter is a lambda expression, then we can write the lambda expression without parentheses
  • if we have only one parameter in a lambda expression, and we do not use it, we can omit itwhen a lambda has only one parameter and Kotlin can figure the signature out itself, we do not have to declare that parameter. Kotlin will declare it for us under the name “it”
  • return inside an lambda expression will return from the enclosing function

Anonymous functions

As a block:

As an expression:

Overview

  • Anonymous functions are like regular functions, but without a name
  • parameter types can be omitted if they can be inferred from context
  • parameters are always passed inside the parentheses. If the last parameter of a function is an anonymous function, the anonymous function cannot go outside the parentheses (this works only for lambdas)!
  • return inside an anonymous function will return from the anonymous function itself

You can learn more from https://kotlinlang.org/docs/reference/lambdas.html#lambda-expressions-and-anonymous-functions

Introduction to Functions – Kotlin

In this post, I will try to explain how to write functions in Kotlin by doing a parallel with Java. It’s not rocket science or anything special in this post, but this is the way I understand and remember better how to write in Kotlin, myself (it’s something new to me too 🙂 ), so maybe this post will help others too.

Defining functions

Kotlin

Java

 

Writing function/method declaration analysis

  • in both Kotlin and Java, we start writing with the access/visibility modifier “private”Note! In Kotlin, we do not have to write the visibility modifier “public“. It can be omitted, regarding that is the default visibility when no explicit modifier is provided.
  • next, in Kotlin we have to use the “fun” keyword, in order to specify that it is a function. Instead, in Java, we have to write the return type of the method/function.
  • next, in both languages we have to write the name of the method/function
  • after the name, we have to write parameters between “()” in both languages. The differences appear in writing the parameters. In Java we wrote the type and then the name of the param (int a), whereas in Kotlin we have to write the name first, “:” and then the type (a: Int). Note that the int type in Kotlin starts with capital i (Int). If there are more parameters, they are separated with “,” (in Java and Kotlin).
  • next, in Java we would open “{“, but in Kotlin, we have to add “:” and then the return type of the function, and only after that we would open “{” ( (a: Int, b: Int): Int { ). So, the return type in Java is written at the beginning, and in Kotlin at the end of the function/method declaration. NOTE: When there is no return type: in Java we use void, whereas in Kotlin we use Unit (or we can omit writing Unit).
  • next, in the body of the method we write the code we need (in this example a sum of a + b). Notice that in Java we MUST add “;” at the end of sum expression (return a + b;), whereas in Kotlin, is not a must. You can add it, but is redundant.

 

Java Kotlin
private private
int fun
sum sum
( (
int a, int b a: Int, b: Int
) )
{ :
return a + b; Int
} {
return a + b
}

Syntax

Kotlin

visibility fun name(paramName1: type, paramName2: type): returnType {

        expresion

}

Java

visibility returnType name(type paramName1, type paramName2) {

       expresion;

}

Shorter way of writing the above method in Kotlin

This is called a function with an expression body and inferred return type. Inferred type means that the compiler deduced the return type of the expression, so we don’t have to write it explicitly. I like this pretty much as it looks clean and easy to read.

Function returning nothing (in Java, void)

Or

You can learn more at http://kotlinlang.org/docs/reference/basic-syntax.html

Kotlin – Hello world

Introduction

What is Kotlin?

It is a new programming language built by JetBrains, and as you may already know, Google announced at Google I/O 2017, that they will now officially support this language. It is inspired by existing languages such as Java, C#, JavaScript, Scala and Groovy.

What are the advantages of using Kotlin?

  • it’s a more concise language (40% cut in the number of lines of code)
  • less NullPointerException errors by making all types non-nullable by default
  • New features like:
    • smart casting
    • high order functions
    • Coroutines
    • Lambdas, etc

Hello World, Kotlin

Let’s create a Hello World project. Create a new project by checking Kotlin option that is available starting with Android Studio 3.0 (Note! If you already have a project and want to convert it to Kotlin, Android Studio has an option to do this too, but we will talk about it in another post).

Step 1

File – New – New Project

Step 2

Step 3

Step 4

Step 5

Step 6

Notice that a kotlin-android plugin was added to the module gradle file.

Step 7

Also, notice these changes in the project build.gradle file.

activity_main.xml

MainActivity

Now, in the MainActivity class, the onCreate() method, looks like this:

As you can see there are changes in the writing (obviously :P):

  • instead of “MainActivity extends AppCompatActivity” now we have to use “:
  • onCreate is now a function
  • the onCreate parameters look like this now “savedInstanceState: Bundle?” (we will get more into this in other posts)

COOL FACT: Notice that we could set a text on our TextView without using findViewById()! We just wrote the id itself and set the text and that’s it. Cool, ha? 🙂