Kotlin Variables and Data Types

Learn via video courses
Topics Covered

Overview

Kotlin data types are categories of data types that provide potential values and actions that may be carried out on the data.

Introduction

Kotlin has primitive and non-primitive data types

The most fundamental kotlin data type though is primitive data type, while reference types like array and string are used for all other data types. Kotlin data types are provided as objects, unlike Java, which requires wrappers java.lang.Integer for primitive data types to behave like objects.

Types of primitive kotlin data types:

  • Boolean
  • Byte
  • Char
  • Double
  • Float
  • Int
  • Long
  • Short

Types of non-primitive kotlin data types:

  • Arrays
  • Class
  • Enum
  • List
  • Map
  • Nothing
  • Set
  • String
  • Unit

We'll look at some of these data types in-depth further in this article

Declaring Variables in Kotlin

For the purpose of creating a variable in kotlin, we can use var or val, and assign a value to it with the equal sign =

Syntax

Example

Variables in kotlin declared with the var keyword can be updated or modified, in contrast to val variables, which cannot.

Variables in Kotlin do not need to be declared with a specific type ("String" for text or "Int" for numbers), unlike many other programming languages.

Kotlin is intelligent enough to recognize that 2015 is an Int (number) variable and that "Scalar Topics" is a String (text).

But if you do want to specify the type, this is how you can do it

Another option is to declare a variable in kotlin without giving it a value and give it one later. But you can only do this if you specify the type.

A variable in kotlin may have a brief name (such as x and y) or a name with more context (such as age, sum, or totalVolume).

In order to name a kotlin variable there are several rules to keep in mind:

  • Variable names can contain letters, digits, underscores, and dollar signs
  • They should start with a lowercase letter and it cannot contain whitespace
  • It also begin with $ and _
  • Variable Names in kotlin are case sensitive ("nextValue" and "nextvalue" are different variables)
  • Reserved words (like Kotlin keywords, such as var or String) cannot be used as names

Basic Data Types in Kotlin

Number

Number types are divided into two groups:

1. Integer types These types store whole numbers, positive or negative, without decimals. Types of integer numbers are Byte, Short, Int and Long.

TypeSize(bits)Min ValueMax Value
Byte8-128127
Short16-3276832767
Int32-2^312^31 - 1
Long64-2^63-2^63 -1

a) Byte

Whole numbers between -128 and 127 can be stored using the Byte data type. When you know the number will be between -128 and 127, use this in instead of Int or other integer types to conserve memory:

Example

b) Short

The Short data type can store whole numbers from -32768 to 32767:

Example

c) Int

The Int data type can store whole numbers from -2147483648 to 2147483647:

Example

d) Long

The Long data type can store whole numbers from -9223372036854775807 to 9223372036854775807. This is used when Int is not large enough to store the value. Optionally, you can end the value with an "L":

Example

2. Floating point types

Kotlin offers IEEE 754 compliant floating-point types Float and Double for real numbers. While Double reflects double precision, Float reflects the single precision defined by IEEE 754 standards.

These kinds store floating-point values with various degrees of precision and range in size:

TypeSize (bits)Significant bitsExponent bitsDecimal digits
Float322486-7

Output

Character

The type Char is used to represent characters. '1' is the character literal that should be enclosed in single quotes.

Small letters (a–z), capital letters (A–z), numbers (0–9), and other symbols are represented by character data types.

Data TypeBitsMin ValueMax Value
char16 bits‘\u0000’ (0)‘\uFFFF’ (65535)

Output:

Special characters start from an escaping backslash \

SymbolMeaning
\ttab
\bbackspace
\nnew line (LF)
\rcarriage return (CR)
\'single quotation mark
\"double quotation mark
\\backslash
\$dollar sign

Boolean

The only information that a boolean data type can convey is either true or false. Kotlin and Java both use the same Boolean type.

Data TypeBitsData Range
boolean1 bittrue or false

Note: Boolean also has a nullable counterpart Boolean? which also has the null value.

Following are the built-in operations on booleans include:

SymbolMeaning
\\disjunction (logical OR)
&&conjunction (logical AND)
\\ and &&work lazily
!negation (logical NOT)

Array

An array is one of the most basic types of data structures. The concept of an array is to group together elements of the same data type, such strings or integers, under a single variable name. Data using arrays is organised so that it is simple to sort or search for a related set of values.

Basic properties of arrays:

  • They are stored in contiguous memory locations.
  • they can be accessed programmatically through their indexes (such as: array[1])
  • They are mutable and of a fixed size.

In Kotlin, arrays are not a native data type, but a mutable collection of similar items which are represented by the Array class.

Define an array class in kotlin

There are two ways to define an array in Kotlin.

1. Using the arrayOf() function

Syntax

Example:

Output

2. Using the Array constructor

Syntax:

Example:

Output:

Access array elements

Two ways by which we can access array elements in kotlin

1. get() and set() operators

Since array in kotlin is a class thus we can access the data of a class object via its member functions such as the get() and set() functions.

The get() method which takes the index of the element and returns the value of item at that index.

Syntax:

The set() method takes 2 parameters:

  • The index of the element the array
  • Value to be inserted

Syntax:

The above code sets the value of the second element in the array to 3

2. indexOf() method

To modify an array element, we should do:

Note: The Index operator [ ] internally is an overloaded operator and stands for calls to the get() and set() member functions.

String

AA string is a collection of characters. Although Kotlin strings have some new functionalities introduced, they are generally identical to Java strings. Since Kotlin strings are immutable by nature, their elements and length cannot be changed.

The String class in Kotlin is defined as:

To declare a string in Kotlin, we need to use double quotes” “ and not single quotes.

Syntax:

or

This is how you can create an empty string

Type Inference

The compiler automatically determines the type with the smallest range large enough to represent the value when you initialize a variable without specifying its type explicitly. The type is Int if it does not go beyond the range of an Int. Long is the type if it exceeds. Add the suffix L to the value in order to explicitly define the Long value. The compiler checks the value to ensure it doesn't go outside the range of the specified type when a type is explicitly specified.

There are two kinds of type inference supported by Kotlin.

  1. Local type inference: with the aim of inferring types of expressions locally, in statement/expression scope.
  2. Function signature type inference: with the aim of inferring types of function return values and/or parameters.

Additionally, Kotlin offers flow-sensitive types via smart casts, which directly impact type inference.

Smart casts are a constrained variant of flow-sensitive typing introduced by Kotlin. Because of flow-sensitive typing, some program expressions may alter the compile-time types of variables. In situations when their runtime types are assured to adhere to the anticipated compile-time types, this enables one to avoid the need for unnecessary explicit casting of values.

Conclusion

  1. Kotlin already provides all data types as objects, unlike Java, which requires wrappers (java.lang.Integer) for primitive data types to behave like objects.
  2. The compiler automatically determines the type with the smallest range large enough to represent the value when you initialize a variable without specifying its type explicitly.
  3. Kotlin strings are immutable by nature, their elements and length cannot be changed.
  4. Data using arrays is organised so that it is simple to sort or search for a related set of values
  5. Variables in Kotlin do not need to be declared with a specific type ("String" for text or "Int" for numbers), unlike many other programming languages.