Data Types in Kotlin

Kotlin is a programming language which compiles to Java Bytecode. It is possible to use Java & Kotlin within the same project. Kotlin is supported by Google and is recommended for Mobile Android Application Development. Today, we will be talking about Data Types within Kotlin.

Prerequisites

Choose one of the following ways to compile Kotlin

Numbers

A mechanism within Kotlin known as Type inference / Deduction helps Kotlin detect which datatype should be assigned to a variable. In Java, we have to explicitly assign data types along with a variable but in Kotlin it is much more simplified. In Kotlin, developers just write down the required value and assign it to a variable which then using the deduction mechanism detects the appropriate data type for it and assigns it. Following are the common Data Types in Kotlin

  • Integers types
    1. Long – 64 bit
    2. (Integer) Int – 32 bit
    3. Short – 16 bit
    4. Byte – 8 bit
  • Floating-point types
    • Double – 64 bit
    • Float – 32 bit
  • Commonly used Data Types
    • Boolean
    • String
    • Characters
    • Arrays

Long Kotlin Program

fun main() {
    // Assigning Long value
    val valueOne = 25L  // Long
    val valueTwo = 25L  // Long
    val result = valueOne + valueTwo

    print("Addition result: $result")
}

Output

Addition result: 50

Challenge: Using Long write a program which can calculate Area of a square.

Line 3 and 4, value 25 has an “L” next to it because it denotes the value of Long within Kotlin so if you are willing to assign a long value, an “L” should be at the end of the value. Long values cannot be written as a decimal point number.


Integer (Int) Kotlin Program

fun main() {
    // Assigning Int value
    val valueOne = 5  // Int
    val valueTwo = 5  // Int
    val result = valueOne * valueTwo

    if (result > 30) {
        print("Result: " + result)
    } else {
        print("Let's skip adding")
    }
}

Output

Let's skip adding

Challenge: Change the int values to a higher value and apply arithmetic operations on it. Try solving any errors if they occur.


Short Kotlin Program

fun main() {
    // Assigning Short value
    val valueOne: Short = 5  // Short
    val valueTwo: Short = 5  // Short
    val result = valueOne + valueTwo

    print("Result: $result")
}

Output

Result: 10

Challenge: Try making a function which can add any two values.

In the above program, within line 3 and 4 we are assigning a data type to the variable which contains a value of “5“. To assign a specific data type to a variable within Kotlin, the following syntax is used

val [variable name]: [Data Type] = [value]
  • val – val stands for variable and is used for assigning a variable
  • variable name – variable names are written according to the developer’s choice but it is preferred to write a variable name according to its usage.
  • Data Type – Here we assign a data type to the variable after the colon.
  • value – After the equal sign, we assign the value according to the Data Type assigned.

Byte Kotlin Program

fun main() {
    // Assigning Byte value
    val valueOne: Byte = 1;
    val valueTwo: Byte = 5;
    val result: Byte = (valueOne + valueTwo).toByte()

    var value = 0
    while (value < result) {
        print("$value \t")
        value++
    }
}

Output

0    1   2   3   4   5

Challenge: Try converting the result without the use of helper method and if it’s not possible, comment the reason below.

In the above program, we have converted the result value to Byte Data Type because when an Arithmetic operation is performed on a Short/Byte Data Type they are converted automatically to Int Data Type as Int is a larger data type than Short/Byte. Within line 06 we have used a keyword var which also declares a variable. Following is the difference between var and val

  • var
    • var also stands for Variable which can be changed also known as a mutable variable.
  • val
    • val also stands for Variable of which value cannot be changed. Also known as an immutable variable. Values stored within a val are final values. They cannot be changed once assigned.

Double Kotlin Program

fun main() {
    // Assigning Double values
    val valueOne = 1.2;
    val valueTwo = 5.54;
    val result: Double = valueOne / valueTwo

    print("Result: $result")
}

Output

Result: 0.21660649819494585

Challenge: Try making a program in which a user can input two values and perform Arithmetic Operations on it while using functions.

There are a different Integer & Floating point types which is decimal point numbers. To store decimal based numbers in a variable, always use the Floating point types for example currency. And if you are willing to neglect the values after the decimal point then you can go for Integer types.


Float Kotlin Program

fun main() {
    // Assigning Float values
    val valueOne = 2.2F;
    val valueTwo = 5.254F;
    val result = valueOne - valueTwo

    print("Result: $result")
}

Output

Result: -3.0540001

Challenge: Develop a program which informs the user if the result is even or in odd using Float Data Type.

As mentioned above with the Long data type we have to add an “L” character, same happens here but instead of an “L” we will write “F” because “F” stands for Float and this is how Kotlin differentiates between Long and Float. Whereas, Float values can be in decimal numbers and the character “F” should be written at the end of the value.


Boolean Kotlin Program

fun main() {
    // Assigning Boolean values
    var isEqual = false

    val valueOne = 10
    val valueTwo = 20

    isEqual = valueOne == valueTwo

    if (isEqual) {
        print("isLarger is true")
    } else {
        print("isLarger is false")
    }
}

Output

isLarger is false

Challenge: Using Boolean values, write a small decision-making game.

Boolean is a data type with 2 values only. Either it can be false (0) or true (1) which makes it the best to confirm whether a certain piece of code is executed or not.


String Kotlin Program

fun main() {
    // Assigning String values
    val name = "Android Club"

    if (name.contains("A")) {
        print("$name rocks!")
    } else {
        print("What are we talking about?")
    }
}

Output

Android Club rocks!

Challenge: Write a program using Functions & Strings which can output the length of the String passed to it.

A string is a very common Data T

ype mostly in every Programming Language. Strings within Kotlin are written between double quotes.


Character Kotlin Program

fun main() {
    // Assigning Character values
    val v1 = 'K'
    val v2 = 'o'
    val v3 = 't'
    val v4 = 'l'
    val v5 = 'i'
    val v6 = 'n'

    print("$v1$v2$v3$v4$v5$v6")
}

Output

Kotlin

Challenge: Try optimizing the code by using one set of characters and displaying the same result using a loop

Arrays Kotlin Program

fun main() {
    // Assigning an Array
    val arrayOne = arrayOf(1, 2, 3, 4, 5)
    val arrayTwo = arrayOf('K', 'o', 't', 'l', 'i', 'n')
    val mixedArray = arrayOf('c', "string", 1, 2.5f)

    // Printing all int values within an Array
    for (value in arrayOne) {
        print("$value ")
    }

    println()

    // Printing all character values within an Array
    for (value in arrayTwo) {
        print("$value")
    }

    println()

    // Printing all mixed Arrays
    for (value in mixedArray) {
        print("$value, ")
    }

    // Printing a single value from an Array
    println("\nFirst value: " + arrayOne[0])
    println("Last value: " + arrayOne[4])
    println("Unknown value: " + arrayOne[5])
}

Output

1 2 3 4 5 
Kotlin
c, string, 1, 2.5, 
First value: 1
Last value: 5
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5

Challenge: Try resolving the error within the above program using conditions.

Arrays are one of the most important components in Kotlin and they can be declared in many ways. We used the most common ones. Arrays are Data Structure which contains elements in groups. These elements can be of mixed data type or of a single data type within an Array.


We have covered the most basic Data types within Kotlin. Data Types come with helper methods too. Every Data Type has powerful helper methods to perform multiple actions.

Related:

  • Arrays in Kotlin
  • Loops and Conditions in Kotlin
  • Android Calculator (Kotlin)