Sitemap

All About Data Types In KOTLIN

9 min readOct 2, 2024

--

Press enter or click to view image in full size
By Mohd Faisal

What we are going to cover in this exercise:

  1. What is Data-Types.
  2. Data-Types in Kotlin along with (Definition, Declarations, Alternatives).

2.1 Character.

2.2 String.

2.3 Boolean

2.4 Array

2.5 Number
2.5.1 Int
2.5.2 Long
2.5.3 Float
2.5.4 Double
2.5.5 Short
2.5.6 Byte

3. Size Chart of Data-Types.

4. Other Data-Types in Kotlin
4.1 Any
4.2 Nothing
4.3 Unit

5. Conclusion

1. What is Data-Types?.

A Data Type is a way to classify different types of data in programming. It tells the system what kind of data is being used, like numbers, text, or true/false values. Data types help the system understand how to handle and store the information correctly.

2. Data-Types in Kotlin.

2.1 Character:

In Kotlin, the Char data type is used to represent a single character. Each character is enclosed in single quotes (' '). It can store a single Unicode character, and the value must be a single character, not a string.

  • Definition:- Char in Kotlin is a primitive type representing a single 16-bit Unicode character.
  • Declaration:-
//with-specification
val letter: Char = 'A'
var letter: Char = 'B'

//auto-specification
val letter = 'A'
var letter = 'B'
  • Alternative:- An alternative to using the Char data type is using String for a sequence of characters, though a string can contain multiple characters, while Char is only for single characters. Here's how you would declare a string:
//even though it's a single character, it's still a String
val word: String = "A"

2.2 String:

In Kotlin, the String data type is used to represent a sequence of characters. Strings are immutable, meaning that their value cannot be changed once created.

  • Definition:- String is a sequence of characters, represented as an immutable collection of Char values. It is a class in Kotlin, and it is widely used for handling and manipulating textual data.
  • Declaration:-
//with-specification
val greeting: String = "Hello, Kotlin!"
var greeting: String = "Hello, Kotlin!"

//auto-specification
val greeting = "Hello, Kotlin!"
var greeting = "Hello, Kotlin!"
  • Alternative:- Kotlin also supports StringBuilder for creating mutable sequences of characters, which allows you to modify the string contents:
val stringBuilder = StringBuilder("Hello")
stringBuilder.append(", Kotlin!")

2.3 Boolean:

In Kotlin, the Boolean data type represents a value that can be either true or false. It is used for conditional expressions and logical operations.

  • Definition:- Boolean is a primitive type in Kotlin that can hold one of two values: true or false. It is often used in control flow statements like if, when, and loops.
  • Declaration:-
//with-specification 
val isKotlinFun: Boolean = true

//auto-specification
val isKotlinFun = true
  • Alternative:- An alternative way to represent true/false values in Kotlin is by using Boolean expressions. These expressions evaluate conditions and return a Boolean value. For example:
val number = 10
val isEven: Boolean = (number % 2 == 0) //Evaluates to true if number is even

2.4 Array:

In Kotlin, an Array is a data structure that can hold a fixed number of elements of a specific type. Arrays are mutable, which means you can change the values of their elements after the array has been created.

  • Definition:- An Array in Kotlin is a collection that holds a fixed number of values of the same type. It can be created using the arrayOf function, and its elements can be accessed using indices.
  • Declaration:-
//with-specification
val numbers: Array<Int> = arrayOf(1, 2, 3, 4, 5)

//auto-specification
val numbers = arrayOf(1, 2, 3, 4, 5)

//empty array with-specification
val emptyArray: Array<Int> = arrayOf()
  • Alternative:- An alternative to Array is using List, which is a more flexible collection type in Kotlin that can grow dynamically and provides various functions for manipulation. However, List is immutable by default; to create a mutable list, you can use mutableListOf.
val listOfNumbers: List<Int> = listOf(1, 2, 3, 4, 5) // Immutable List
val mutableListOfNumbers: MutableList<Int> = mutableListOf(1, 2, 3, 4, 5) // Mutable List

2.5 Number:

In Kotlin, the Number class serves as a superclass for all numeric types, including Int, Double, Float, Long, Short, and Byte. It is an abstract class that provides a common interface for numeric types, allowing for type-safe arithmetic operations.

  • Definition:- Number is a class in Kotlin that represents numeric values. It provides methods to convert to various numeric types (like Int, Double, etc.) and serves as a superclass for all numeric types.
  • Declaration:-
val num: Number = 42 // Can be an Int
val numDouble: Number = 42.0 // Can be a Double
val numFloat: Number = 42f // Can be a Float

// Convert to Int
val intValue: Int = num.toInt()
// Convert to Double
val doubleValue: Double = num.toDouble()
// Convert to Float
val floatValue: Float = num.toFloat()
  • Alternative:- While you can use Number to hold numeric values, it is more common in Kotlin to use specific numeric types directly for type safety and performance. For example:
val intNum: Int = 10
val doubleNum: Double = 20.5
val floatNum: Float = 15.5f

2.5.1 Int:

In Kotlin, Int is a primitive data type that represents a 32-bit signed integer. It is one of the most commonly used numeric types for whole numbers.

  • Definition:- Int is a built-in data type in Kotlin that stores integer values in the range from -2,147,483,648 to 2,147,483,647. It is used for arithmetic operations, looping, and counting.
  • Declaration:-
//with-specification
val age: Int = 25

//auto-specification
val age = 25
  • Alternative:- While Int is used for whole numbers, you can use other numeric types for different ranges or precision, such as:
Long //for larger integers (64-bit) 
Short //for smaller integers (16-bit)
Byte //for very small integers (8-bit)

2.5.2 Long:

In Kotlin, Long is a primitive data type that represents a 64-bit signed integer. It is used to store larger integer values than the Int type.

  • Definition:- Long is a built-in data type in Kotlin that stores integer values in the range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. It is typically used when you need to work with numbers that exceed the limits of Int.
  • Declaration:-
//with-specification
val distance: Long = 100000L

//auto-specification
val distance = 100000L
  • Alternative:- If you need to work with smaller integer values, you can use Int, Short, or Byte. Conversely, if you need larger values with a higher precision (especially for decimal numbers), you might consider using Double.

2.5.3 Float:

It is used to store decimal values, especially when memory efficiency is a priority. Float is typically employed when the range of values is limited, and high precision is not required, making it suitable for applications like graphics and scientific computations.

  • Definition:- In Kotlin, Float is a primitive data type that represents a 32-bit single-precision floating-point number.
  • Declaration:- To declare a Float variable in Kotlin, you can use the suffix f (or F) to indicate that the number is of type Float:
//with-specification
val temperature: Float = 36.5f

//auto-specification
val temperature = 36.5f
  • Alternative:- If you need higher precision for decimal numbers, you can use Double, which is a 64-bit double-precision floating-point type.

2.5.4 Double:

In Kotlin, the Double data type is a built-in type that represents a double-precision 64-bit IEEE 754 floating point. It is commonly used for representing decimal values.

  • Definition:- A data type that can hold large numbers with decimals, allowing for a greater range and precision than a Float.
  • Declaration:-
//with-specification
val pi: Double = 3.14159 //Immutable
var pi: Double = 3.14159 //Mutable

//auto-specification
val pi: Double = 3.14159 //Immutable
var pi: Double = 3.14159 //Mutable
  • Alternative:- If you need a data type with less precision and range, you can use Float, which represents a single-precision 32-bit IEEE 754 floating point.

2.5.5 Short:

In Kotlin, the Short data type is a built-in type that represents a 16-bit signed integer. It is used for storing small integer values when memory efficiency is a concern.

  • Definition:- A data type that can hold integer values ranging from -32,768 to 32,767. It occupies 2 bytes of memory.
  • Declaration:-
//with-specification
val smallNumber: Short = 1500 //Immutable
var smallNumber: Short = 1500 //Mutable

//converstion
val count = 1000.toShort()
  • Alternative:- If you need a data type that can store larger integer values, you can use Int, which is a 32-bit signed integer. Here’s how you can declare an Int.

2.5.6 Byte:

In Kotlin, the Byte data type is a built-in type that represents an 8-bit signed integer. It is useful for saving memory when you know the values will be within a small range.

  • Definition:- A data type that can hold integer values ranging from -128 to 127. It occupies 1 byte of memory.
  • Declaration:-
//with-specification
val smallValue: Byte = 100 //Immutable
var smallValue: Byte = 100 //Mutable

//converstion
val count = 50.toByte()
  • Alternative:- If you need a data type that can store larger integer values, you can use Short, Int, or Long, depending on the range required. Here’s how you can declare a Short.

3. Size chart of Data-Types:

Made from Github-Gist

4. Other Data-Types in Kotlin:

4.1 Any

Get Mohd Faisal’s stories in your inbox

Join Medium for free to get updates from this writer.

4.2 Noting

4.3 Unit

4.1 Any:

In Kotlin, the Any data type is a built-in type that serves as the root of the Kotlin class hierarchy. Every class in Kotlin inherits from Any, making it a versatile type for handling various data types.

  • Definition:- The superclass of all non-nullable types in Kotlin. It can represent any value, whether it’s a primitive type, a reference type, or a combination of types.
  • Declaration:-
// Using val (immutable)
val number: Any = 42 // This can hold an Int
val text: Any = "Hello" // This can hold a String
val list: Any = listOf(1, 2, 3) // This can hold a List

// Using var (mutable)
var anything: Any = "Kotlin"
anything = 3.14 // Now it holds a Double
  • Key Points:-
  1. Use Any when you need a variable to hold values of different types, especially when the type can change dynamically.
  2. Avoid using Any when the specific type is known, as it sacrifices type safety and can lead to runtime type checking and casting.

4.2 Nothing:

In Kotlin, the Nothing type is a special type that signifies the absence of a value. It is used in scenarios where a function or expression never successfully completes, either because it always throws an exception or because it enters an infinite loop.

  • Definition:- A type that has no instances. It is a subtype of all types and is used to indicate that a particular code path cannot return a value. For example, functions that always throw exceptions have a return type of Nothing.
  • Declaration:- You typically don’t declare variables of type Nothing, as it cannot hold any value. Instead, it is primarily used in function return types and expressions.
// Function that never returns (throws an exception)
fun fail(message: String): Nothing {
throw IllegalArgumentException(message)
}

// Function that enters an infinite loop
fun infiniteLoop(): Nothing {
while (true) {
// Do something
}
}

// Using Nothing in a when expression
fun handleInput(input: Any) {
when (input) {
is String -> println("Input is a string: $input")
is Int -> println("Input is an integer: $input")
else -> throw IllegalArgumentException("Unknown type")
}
}
  • Key Points:-
  1. Use Nothing to indicate functions that do not complete normally, such as those that throw exceptions or enter infinite loops.
  2. It can be useful in when expressions or to signal error conditions in your code.

4.3 Unit:

In Kotlin, the Unit type is a special type that represents the absence of a meaningful value. It is similar to void in languages like Java and C++, indicating that a function does not return any value.

  • Definition:- A type that has exactly one instance: Unit. It is used as the return type for functions that do not return any meaningful value.
  • Declaration:- You can declare a function with a return type of Unit, though it is optional, as Kotlin infers Unit as the return type when no value is returned. Here are a few examples:
// Function that returns Unit explicitly
fun printMessage(message: String): Unit {
println(message)
}

// Function that returns Unit implicitly (return type can be omitted)
fun displayGreeting() {
println("Hello, World!")
}

// Calling the functions
printMessage("Hello, Kotlin!")
displayGreeting()
  • Key Points:
  1. Use Unit for functions that do not need to return a value.
  2. It can be used to improve code readability by explicitly stating that a function is intended for side effects rather than returning data.
  3. The Unit type is particularly useful in Kotlin for defining functions that perform operations (like printing to the console or updating a state) without producing a value that needs to be used. It provides clarity in function signatures and supports Kotlin's functional programming style.

6. Conclusion:

In conclusion, understanding data types in Kotlin is essential for writing efficient and effective code. By leveraging the rich set of built-in data types, including primitive types and collections, developers can create robust applications that handle data seamlessly. The strong type system not only enhances code readability but also minimizes runtime errors, leading to a more enjoyable programming experience. As you continue to explore Kotlin, remember that mastering data types will empower you to harness the full potential of this versatile language, paving the way for your growth as a skilled Kotlin developer.

--

--

Mohd Faisal
Mohd Faisal

Written by Mohd Faisal

0 followers

Software Engineer