Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Using Kotlin in Android Studio 3.0 (Part 2)

DZone's Guide to

Using Kotlin in Android Studio 3.0 (Part 2)

Learn more about the basic syntax of the Kotlin language and see how to get started using it in your Android apps.

· Mobile Zone ·
Free Resource

Introduction

In the previous article, I introduced how to install and create a simple Android application using Kotlin in Android Studio 3.0. In this article, I will continue to introduce the basic syntax of Kotlin and write some Kotlin code in Android Studio 3.0.

The Basics in Kotlin

Basic Types

In Kotlin, everything is an object. Basic types, such as integers, floats, and characters act as an object. The name of the basic types and the way they work are very similar to Java but there are some differences you might take into account:

  • There are no automatic conversions among numeric types.
  • Characters (Char) cannot directly be used as numbers
  • Bitwise arithmetical operations are a bit different.
  • Literals can give information about its type
  • A String can be accessed as an array and can be iterated

Variables

Variables in Kotlin can be defined as mutable (var) or immutable (val). Examples of variables can look like:

val PI = 3.14
var x:Int = 2
x += 1

Comments

Just like Java, Kotlin also supports end-of-line (//) and block comments (/*…*/)

String Templates

A template expression in Kotlin starts with a dollar sign ($) and consists of either a simple name:

val a = 3
val s = "a = $a" //result: a = 3

or an arbitrary expression in curly braces:

val s = "abc"
val str = "$s.length is ${s.length}" // result:  abc.length is 3

if Expression

In Kotlin, we can either use if as we are used to doing in Java:

var max: Int
if (a > b) {
    max = a
} else {
    max = b
}

or as an expression, i.e. it returns a value:

val max = if (a > b) a else b

when Expression

when expressions are similar to switch/case in Java. This expression will try to match its argument against all possible branches in order until it finds one that is satisfied, it looks like this:

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> {
                print("I am a block")
print("x is neither 1 nor 2")
    }
}

for loop

for loop iterates through anything that provides an iterator as follows:

var S = 0
val n = 5
for (i in 1..n )
     S += i

while loop

while (or do..while) loop works as usual:

var S = 0
val n = 5
var i = 1
while (i <= n )
{
    S += i
    i += 1
}

Functions

Functions (our methods in Java) are declared just using the fun keyword. Function (sum) having two Int parameters with Int return type:

fun sum(a: Int, b: Int): Int {
    return a + b
}

Function returning no meaningful value:

fun printSum(a: Int, b: Int) {
    println("sum of $a and $b is ${a + b}")
}

An Android Application

I have introduced a bit of basic syntax of Kotlin and now, we are going to relax by writing some Kotlin code in Android Studio 3.0. To save time, I am going to reuse MyFirstKotlinApp application in my previous article and add some code inside it.

Deleting TextView that is used in previous article (ID = message). Adding three TextViews

ID

text

numList

@string/numberslist

evenList

@string/evenlist

oddList

@string/oddlist

strings.xml file looks like this:

<resources>
    <string name="app_name">My First Kotlin App</string>
    <string name="numberslist">Numbers List</string>
    <string name="evenlist">Even numbers List</string>
    <string name="oddlist">Odd numbers List</string>
</resources>

Selecting the activity_main.xml and adding something for the numList TextView in Text mode

<TextView
    android:id="@+id/numList"
    android:layout_width="250dp"
    android:layout_height="50dp"
    android:text="@string/numberslist"
    android:textColor="#ff0000"
    android:textSize="20dp"
    …/>

the evenList TextView

<TextView
    android:id="@+id/evenList"
    android:layout_width="250dp"
    android:layout_height="50dp"
    android:text="@string/evenlist"
    android:textColor="#ff0000"
    android:textSize="20dp"
    …/>

and the oddList TextView

<TextView
    android:id="@+id/oddList"
    android:layout_width="250dp"
    android:layout_height="50dp"
    android:text="@string/oddlist"
    android:textColor="#ff0000"
    android:textSize="20dp"
… />

Selecting the MainActivity.kt, adding some functions to Activity class:

// displays integers from 1 to n and calculates sum of them
     fun numList (n:Int):String
     {
         var S = 0
         var str = ""
         for(i in 1..n)
         {
             S = S + i
             str += " $i"
         }

         return "Sum of [ $str ] = $S"
     }
    // displays even integers from 1 to n and calculates sum of them
    fun evenList (n:Int):String
    {
        var S = 0
        var str = ""
        for(i in 1..n)
        {
            if(i%2 == 0)
            {
                S = S + i
                str += " $i"
            }
        }

        return "Sum of [ $str ] = $S"
    }
// displays odd integers from 1 to n and calculates sum of them
    fun oddList (n:Int):String
    {
        var S = 0
        var str = ""
        for(i in 1..n)
        {
            if(i%2 != 0)
            {
                S = S + i
                str += " $i"
            }
        }

        return "Sum of [ $str ] = $S"
    }
}

Adding some code to the onCreate()method:

numList.text = numList(5)
evenList.text = evenList(5)
oddList.text = oddList(5)

The complete code in MainActivity.kt file:

package com.example.admin.myfirstkotlinapp

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        numList.text = numList(5)
        evenList.text = evenList(5)
        oddList.text = oddList(5)
    }

     // displays integers from 1 to n and calculates sum of them
     fun numList (n:Int):String
     {
         var S = 0
         var str = ""
         for(i in 1..n)
         {
             S = S + i
             str += " $i"
         }

         return "Sum of [ $str ] = $S"
     }

    // displays even integers from 1 to n and calculates sum of them
    fun evenList (n:Int):String
    {
        var S = 0
        var str = ""
        for(i in 1..n)
        {
            if(i%2 == 0)
            {
                S = S + i
                str += " $i"
            }
        }

        return "Sum of [ $str ] = $S"
    }

// displays odd integers from 1 to n and calculates sum of them
    fun oddList (n:Int):String
    {
        var S = 0
        var str = ""
        for(i in 1..n)
        {
            if(i%2 != 0)
            {
                S = S + i
                str += " $i"
            }
        }

        return "Sum of [ $str ] = $S"
    }
}

Run the app and the result should look like the following screenshot:

Image title

Conclusion

In this article, I have introduced some basic syntax of the Kotlin language and demonstrated an example in Android Studio 3.0. In my next article, I will introduce some other features of Kotlin.

Topics:
mobile ,mobile app development ,kotlin ,android

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}