Table of contents
1.
Introduction
2.
Kotlin Data Types
2.1.
Numbers
2.1.1.
Integer Data types
2.1.2.
Floating-point Data types
2.2.
Boolean
2.3.
Characters
2.4.
Strings
3.
Kotlin Data Types and type conversion
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

Kotlin Data Types and Type Conversion

Author Tanay kumar Deo
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Kotlin, an open-source programming language like PythonJavascript, etc. This language is commonly used for Android Development by developers.

Just like other programming languages, Kotlin also has Data Types for variables. The most basic Kotlin Data type is the primitive data type. In Java, we need to use wrappers (Java.lang.Integer ) for Primitive data types to behave like an Object. But in Kotlin, all the data types already act as objects.

This article will learn about different Kotlin data types and type conversion.

Kotlin Data Types

In this section, we will learn about Kotlin data types. Data types in Kotlin are divided into the following groups:

  • Numbers
  • Booleans
  • Characters
  • Strings

Numbers

  We have two data types to manage numbers in Kotlin.

Integer Data types

Integer data types store whole, positive or negative numbers (such as 121 or -457) without decimals. We have four types with different sizes and value ranges in Integer data types.

Data type

Bits

Min Value

Max Value

byte 8 bits -128 127
short 16 bits -32768 32767
int 32 bits -2147483648 2147483647
long 64 bits -9223372036854775808 9223372036854775807

 

Example usage of these data types can be seen below:

val two = 2  // Int
val twoBillion = 2000000000 // Long
val twoLong = 2L // Long
val twoByte: Byte = 2 // Byte
You can also try this code with Online Java Compiler
Run Code

Floating-point Data types

Floating-point Data types represent numbers with the fractional part containing one or more decimals values. We have two types with different sizes and value ranges in floating-point data types.

Data type

Bits

Min Value

Max Value

float 32 bits 1.40129846432481707e-45 3.40282346638528860e+38
double 64 bits 4.94065645841246544e-324 1.79769313486231570e+308

 

Example usage of these data types can be seen below:

val pi = 3.141 // Double
// val two: Double = 2 // Error: type mismatch
val oneDouble = 1.0 // Double


val e = 2.7182818284 // Double
val eFloat = 2.7182818284f // Float, actual value is 2.7182817
You can also try this code with Online Java Compiler
Run Code

 

Note: If we don't specify the data type for any numerical variable, it is most often considered as Int type for whole numbers. Similarly, for floating-point numbers, Double is considered.

Boolean

The Boolean data type can only store the values of either true or false. It is a one-bit data type.

Data type

Bits

Values

boolean 1 bit true or false

 

Example usage of this data types can be seen below:

val a: Boolean = true
val b: Boolean = false


println(a || b)  // The Output will be true or 1.
println(a && b) // The output will be false or 0.
You can also try this code with Online Java Compiler
Run Code

Characters

The Character data type can only store a single character, i.e., alphabets from (a-z) and ( A - Z), digits from ( 0 - 9), other symbols, and special characters. The type char represents it.

Data type

Bits

Range

char 8 bits -127 to 128

 

Note: Special characters starts with the ‘\' ( escaping backspace ). For example, most common special characters are: ‘\t', ‘\n', ‘\b', etc.

Example usage of this data type can be seen below:

val anyChar: Char = 'a'
println(anyChar)
println('\n') // Prints an extra newline character
You can also try this code with Online Java Compiler
Run Code

Strings

Strings Data types:- The String data type can store a sequence of characters. The string value is the sequence of characters enclosed in double quotes ("").

Example usage of string data types can be seen below:

val str = "Hello World"
println(c) // Prints Hello World
You can also try this code with Online Java Compiler
Run Code

 

Strings literals:- Literals are the source code representation of any fixed values. For example, "Hey CodingNinjas!" is a string literal that will appear directly in a program without requiring any computation (like variables).

We have two types of string literals in Kotlin:

  • escaped strings containing escaped characters (like \n, \t, \b).
  • raw strings that contain arbitrary text and newlines. A raw string is delimited by a triple quote (""").

Example usage of string literals can be seen below:

// Example of escaped string
val str = "Hello, world!\n"


// Example of raw string
val text = """
    for (c in "foo")
        print(c)
"""
You can also try this code with Online Java Compiler
Run Code

Kotlin Data Types and type conversion

Till now, we have learned about Kotlin data types. In this section, we will learn about type conversion in Kotlin. Type conversion (AKA Type Casting) is done to change the entity of any variable from one data type to another data type. Unlike Java, Kotlin doesn't support implicit type conversion, i.e., we cannot assign an integer value to a long data type. For example,

var myNumber = 10 // Integer data type
var myLongNumber: Long = myNumber       // Compiler error (Implicit conversion)
// Type mismatch: inferred type is Int, but Long was expected
You can also try this code with Online Java Compiler
Run Code

 

To know more about the type conversion and type casting in Java, refer to the blog Type Conversion And Type Casting In Java.

In Kotlin, we can use helper functions for explicit data type conversion. With these helper functions, we can type conversion from smaller to larger data types and larger to smaller data types. We can use the following available helper functions for type conversion in Kotlin:

  • toByte().
  • toShort(). 
  • toInt() .
  • toLong(). 
  • toFLoat(). 
  • toDouble(). 
  • toChar().

Now, let's see an example for Kotlin data types and type Conversion.

fun main(args: Array<String>)
{
            val num1: Int = 259
            val num2: Int = 50000
            val longNum1: Long = 21474847499
            val doubleNum: Double = 22.55


    println(num1 + " to byte: " + (num1.toByte()))
    println(num2 + " to short: " + (num2.toShort()))
    println(longNum1 + " to Int: " + (longNum1.toInt()))
    println(doubleNum + " to Int: " + (doubleNum.toInt()))
    println(num1 + " to float: " + (num1.toFloat()))
    println("A to Int: " + ('A'.toInt()))
    println("65 to char: " + (65.toChar()))
}
You can also try this code with Online Java Compiler
Run Code

In the above example, we dealt with Kotlin data types and type conversion by initiating a few variables of different types and then using helper functions for explicit type conversion. Let's see the output of the above code: 

259 to byte: 3
50000 to short: -15536
21474847499 to Int: 11019
22.55 to Int: 22
259 to float: 259.0
A to Int: 65
65 to char: A

Must Read Elvis Operator Kotlin

We have successfully completed our tutorial on Kotlin data types and type conversion. Now let's see some frequently asked questions.

FAQs

  1. Which helper function is used for type conversion related to boolean data type?
    In Kotlin, we do not have any helper function for type conversion of boolean data type.
     
  2. What are the differences between type conversion in Java and Kotlin?
    In Java, type conversion is done implicitly, and we can only convert from more minor to more significant data types. While in Kotlin type conversion is done explicitly using the helper function, we can convert variables from smaller to larger data types and larger to smaller data types.
     
  3. Why is double preferred for most calculations?
    The precision of a floating-point value indicates how many digits we can have after the decimal point. And the precision of Float is only 6 or 7 decimal digits, while the same of double variables are about 15 digits. Therefore it is always preferred to use Double for most calculations.

Key Takeaways

In this article, we learned about Kotlin data types and type conversion. First, we implemented different Kotlin data types with a few detailed examples, and then we performed type conversion on these data types with the help of the helper functions in Kotlin.

To study more about data types, refer to Abstract Data Types in C++ and Data Types in C++.

Don't stop here. Check out the blogs Kotlin KeywordsKotlin Decision StatementsKotlin Input/Output, and Getting started with Kotlin.

Also, check out our Android Development Course on the Coding Ninjas Website to learn everything you need to know about Android development and design future applications. Until then, good luck!

We hope you found this blog helpful. Liked the blog? Then feel free to upvote and share it.

Live masterclass