Kotlin Data Types

Mercy Jemosop
2 min readNov 1, 2023

Data Types

Introduction

Data type is a type of value a variable has.

Variable is a container that stores a data value e.g val name =”Mercy’’, in this example name is a variable and “mercy” is a value.

Importance

  • Ensures that the data collected is in the preferred format.
  • The value is as expected.
  • Gather clean and consistent data

Kotlin Data Types

  1. Number :

a. Integer types store whole numbers without a decimal, they number can be negative or positive.

example:

Byte stores whole numbers from -128 to 127, it can be used in place of int to save memory when you are certain of the value

val myNum: Byte = 100

Short stores whole numbers from -32768 to 32767

val myNum: Short = 5000

Int stores whole numbers between -2147483648 to 2147483647

val myNum: Int = 100000

Long stores whole numbers between -9223372036854775807 to 9223372036854775807. You can optionally end the value with an “L”

val myNum: Long = 15000000000L

b. Floating point types, these are numbers containing decimals.

Float its precision is only six/seven decimal digits. it can be a scientific number with an “e” or “E” to indicate the power of 10. e.g val myNum1: Float = 35E3F

val myNum: Float = 5.75F
val myNum1: Float = 35E3F
//is the same as
35000.0

Double has a precision of about 15 digits.

val myNum2: Double = 12E4

2. Booleans

It only takes true or false value.

val isValid: Boolean = true

3. Characters

It is used to store a single character. It is surrounded by single quotes like ‘A’.

val grade: Char = 'B'

4. Strings

It is used to store sequence of characters. It must be surrounded by double quotes.

val hello: String = "Hello World"

Multiline strings

val text = """
for (c in "foo")
print(c)
"""

5. Arrays

They are used to store multiple values in a single character. It is a data structure that holds a fixed number of values of the same type or its subtype.

var riversArray = arrayOf("Nile", "Amazon", "Yangtze")

Access element in an array

println(riversArray[0])

Change an Array Element

riversArray[0] = "Opel"

Array Length / Size

println(riversArray.size)

Check if an Element Exists in an array, you can use the in operator to check if an element exist in an array.

if ("Opel" in riversArray) {
println("It exists!")
}

Loop Through an Array

val riversArray= arrayOf("Volvo", "BMW", "Ford", "Mazda")
for (x in riversArray) {
println(x)
}

Sources:

--

--

Mercy Jemosop

Software Developer. I am open to job referrals. connect with me on twitter @kipyegon_mercy