SoFunction
Updated on 2025-04-12

Android Kotlin Basic Data Type Detailed Explanation

Preface

The basics you need to know when getting started with kotlin.

The basic numerical types of Kotlin includeByte、Short、Int、Long、Float、Doublewait.
Unlike Java, characters do not belong to numeric types, but are independent data types.

type Bit width
Double 64
Float 32
Long 64
Int 32
Short 16
Byte 8

Literal constants

Here are all literal constants of types:

Decimal: 123
Long shape ends with capital L: 123L
Hexadecimal begins with 0x: 0x0F
The binary system starts with 0b: 0b00001011

Note: 8-digit system is not supported

Kotlin also supports floating point values ​​represented by traditional symbols:

Doubles default writing method: 123.5, 123.5e10
Floats uses f or F suffix: 123.5f

You can use underscores to make numeric constants easier to read:

val oneMillion = 1_000_000
val creditCardNumber = 1234_5678_9012_3456L
val socialSecurityNumber = 999_99_9999L
val hexBytes = 0xFF_EC_DE_5E
val bytes = 0b11010010_01101001_10010100_10010010

There is no basic data type in kotlin, only encapsulated numeric types, each of you define one
Variables, actually kotlin helps you encapsulate an object

In kotlin, comparison is divided into numerical comparison and object address comparison. ==, ====

Type conversion

Show conversion/implicit conversion

Display conversion is also called strong rotation, similar to Java. There are slight differences in writing

ToInt() corresponds to java writing ();

Due to different representations, smaller types are not subtypes of larger types, and smaller types cannot be implicitly converted to larger types. This means that we cannot assign the Byte value to an Int variable without explicit conversion.

val b: Byte = 1 // OK, the literal value is static detectionval i: Int = b // mistakeWe can use it on behalf oftoInt()method。
val b: Byte = 1 // OK, the literal value is static detectionval i: Int = () // OK

Each data type has the following methods that can be converted into other types:

toByte(): Byte
toShort(): Short
toInt(): Int
toLong(): Long
toFloat(): Float
toDouble(): Double
toChar(): Char

In some cases, automatic type conversion can also be used, provided that the correct data type can be inferred based on the context and the mathematical operators will be overloaded accordingly. For example, the following is correct:

val l = 1L + 3 // Long + Int => Long

Bit operator

For the Int and Long types, there are also a series of bit operators that can be used, namely:

shl(bits) – Left shift (Java's <<)
shr(bits) – Right shift (Java's >>)
ushr(bits) – 无符号Right shift (Java's >>>)
and(bits) – and
or(bits) – or
xor(bits) – 异or
inv() – Reverse

Boole

Boolean is represented by the Boolean type, which has two values: true and false.
If needed, a nullable reference boolean will be boxed.
Built-in Boolean operations include:

|| – Short circuit logic or
&& – Short circuit logic and
! - Logical non

Array

Array is implemented using the class Array, and there is also a size property and get and set methods. Since the get and set methods are overloaded using [], we can easily get or set the value of the corresponding position of the array through subscripts.
There are two ways to create arrays: one is to use the function arrayOf(); the other is to use factory functions. As shown below, we created two arrays in two ways:

fun main(args: Array<String>) {
    //[1,2,3]
    val a = arrayOf(1, 2, 3)
    //[0,2,4]
    val b = Array(3, { i -> (i * 2) })
//Read the array contentprintln(a[0])    // Output result: 1println(b[1])    // Output result: 2}

As mentioned above, the [] operator represents calling member functions get() and set().
Note: Unlike Java, arrays in Kotlin are invariant.
In addition to the class Array, there are also ByteArray, ShortArray, and IntArray, which are used to represent arrays of various types, eliminating boxing operations, so they are more efficient, and their usage is the same as Array:

val x: IntArray = intArrayOf(1, 2, 3)
x[0] = x[1] + x[2]

character

Unlike Java, Char in Kotlin cannot be directly manipulated with numbers, Char must be included in single quotes.
For example, ordinary characters '0', 'a'.

fun check(c: Char) {
    if (c == 1) { // Error: Type incompatible        // ……
    }
}

Character literals are enclosed in single quotes: ‘1’. Special characters can be escaped with backslashes. These escape sequences are supported: \t, \b, \n, \r, \’, \”, \ and $. To encode other characters, you need to use Unicode escape sequence syntax: '\uFF00'.
We can explicitly convert characters to Int numbers:

fun decimalDigitValue(c: Char): Int {
    if (c !in '0'..'9')
        throw IllegalArgumentException("Out of range")
    return () - '0'.toInt() // explicitly convert to numbers}

When nullable references are required, numbers and characters are boxed. Boxing operations do not retain identity.

String

Like Java, String is unchanged. Square brackets [] syntax can easily obtain a character in a string, or iterate through a for loop:

for (c in str) {
    println(c)
}

Kotlin supports three quotation marks """ to expand strings, supports multi-line strings,

for example:

fun main(args: Array&lt;String&gt;) {
    val text = """
     Multi-line string
     Multi-line string
     """
    println(text)   // There are some pre-spaces for the output}

String can be used to remove unnecessary whitespace through the trimMargin() method.

fun main(args: Array&lt;String&gt;) {
    val text = """
     |Multi-line string
     |
     |Multi-line string
     |Runoob
     """.trimMargin()
    println(text)    // The prefixed space has been deleted}

default|Used as a boundary prefix, but you can select other characters and pass them as parameters, such as trimMargin(">").

String template

A string can contain template expressions, i.e. small pieces of code that evaluate and merge the results into a string.
The template expression begins with the dollar sign ($) and consists of a simple name:

fun main(args: Array&lt;String&gt;) {
    val i = 10
    val s = "i = $i" // The evaluation result is "i = 10"    println(s)
}

Or any expression that is extended with curly braces:

fun main(args: Array&lt;String&gt;) {
    val s = "runoob"
    val str = "$ is ${}" // The evaluation result is "is 6"    println(str)
}

Templates are supported internally by native and escaped strings. If you need to be in native string
The literal value of $ characters (it does not support backslash escape), you can use the following syntax:

fun main(args: Array&lt;String&gt;) {
    val price = """
    ${'$'}9.99
    """
    println(price)  // The evaluation result is $9.99}

This is the end of this article about the basic data types of Android Kotlin. For more information about Android Kotlin data types, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!