Kotlin Basic Data Types

Kotlin's basic numeric types include Byte, Short, Int, Long, Float, Double, etc.

Unlike Java, characters are not a numeric type and are an independent data type.

Integer types

  • Byte: 8-bit, range from -128 to 127.
  • Short: 16-bit, range from -32,768 to 32,767.
  • Int: 32-bit, range from -2^31 to 2^31 - 1.
  • Long: 64-bit, range from -2^63 to 2^63 - 1.

Floating-point types

  • Float: 32-bit, single precision, with 6-7 significant digits.
  • Double: 64-bit, double precision, with 15-16 significant digits.

Character type

  • Char: 16-bit Unicode character.

Boolean type

  • Boolean: has two values:trueandfalse。

String type

  • String: a sequence of characters.

Array type

Kotlin provides array types to store elements of the same type, for example:

  • IntArray: storesInttype array.
  • DoubleArray: storesDoubletype array.
  • Array<T>: generic array, can store any type.
Type Bit width
Double 64
Float 32
Long 64
Int 32
Short 16
Byte 8

Examples

fun main() {
    // Integer types
    val byteValue: Byte = 127
    val shortValue: Short = 32767
    val intValue: Int = 2147483647
    val longValue: Long = 9223372036854775807L

    // Floating-point types
    val floatValue: Float = 3.14F
    val doubleValue: Double = 3.141592653589793

    // Character type
    val charValue: Char = 'A'

    // Boolean type
    val booleanValue: Boolean = true

    // String type
    val stringValue: String = "Hello, Kotlin!"

    // Array type
    val intArray: IntArray = intArrayOf(1, 2, 3, 4, 5)
    val doubleArray: DoubleArray = doubleArrayOf(1.1, 2.2, 3.3)
    val stringArray: Array<String> = arrayOf("Kotlin", "Java", "Python")

    // Print all values
    println("Byte Value: $byteValue")
    println("Short Value: $shortValue")
    println("Int Value: $intValue")
    println("Long Value: $longValue")
    println("Float Value: $floatValue")
    println("Double Value: $doubleValue")
    println("Char Value: $charValue")
    println("Boolean Value: $booleanValue")
    println("String Value: $stringValue")
    println("Int Array: ${intArray.joinToString()}")
    println("Double Array: ${doubleArray.joinToString()}")
    println("String Array: ${stringArray.joinToString()}")
}

Literal constants

The following are literal constants of all types:

  • Decimal: 123
  • Long integers end with uppercase L: 123L
  • Hexadecimal starts with 0x: 0x0F
  • Binary starts with 0b: 0b00001011
  • Note: Octal is not supported

Kotlin also supports floating-point values in traditional notation:

  • Doubles default notation:123.5, 123.5e10
  • Floats use suffix f or F:123.5f

You can use underscores to make numeric constants more readable:

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

Comparing two numbers

In Kotlin, comparing two numbers can use standard comparison operators, including==、!=、<、>、<=and>=. These operators can compare basic data types, such asInt、Double、Floatetc.

fun main() {
    val a: Int = 5
    val b: Int = 10
    val c: Double = 5.0

    // 相等和不相等比较
    println("a == b: ${a == b}")   // 输出 false
    println("a != b: ${a != b}")   // 输出 true

    // 大小比较
    println("a < b: ${a < b}")     // 输出 true
    println("a > b: ${a > b}")     // 输出 false
    println("a <= b: ${a <= b}")   // 输出 true
    println("a >= b: ${a >= b}")   // 输出 false

    // 不同类型的比较
    println("a == c: ${a == c}")   // 输出 true,Kotlin 自动将 Int 转换为 Double 进行比较
    println("a < c: ${a < c}")     // 输出 false
    println("a > c: ${a > c}")     // 输出 false
}
  1. Type conversion: Kotlin automatically performs type conversion when comparing different data types. For example, in the above example,aYesInttype, andcYesDoubletype, Kotlin will automatically convertatoDoubletype for comparison.

  2. Equality: In Kotlin,==operator is used for structural equality comparison, i.e., comparison of values, while===operator is used for referential equality comparison, i.e., whether the objects are the same instance. When comparing basic data types, the==operator is usually used.

fun main() {
    val x: Int = 1000
    val y: Int = 1000

    println("x == y: ${x == y}")   // 输出 true,值相等
    println("x === y: ${x === y}") // 输出 false,不同的实例

    val z: Int = x
    println("x === z: ${x === z}") // 输出 true,引用相同
}

In this example,xandyvalues are equal, but they are different instances, thereforex === yreturnsfalse. Butxandzreference the same instance, sox === zreturnstrue。


Type conversion

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

val b: Byte = 1 // OK, 字面值是静态检测的
val i: Int = b // 错误

We can instead use its toInt() method.

val b: Byte = 1 // OK, 字面值是静态检测的
val i: Int = b.toInt() // OK

Each data type has the following methods that can convert to other types:

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

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

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

Bitwise operators

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

shl(bits) – 左移位 (Java’s <<)
shr(bits) – 右移位 (Java’s >>)
ushr(bits) – 无符号右移位 (Java’s >>>)
and(bits) – 与
or(bits) – 或
xor(bits) – 异或
inv() – 反向

Characters

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

fun check(c: Char) {
    if (c == 1) { // 错误:类型不兼容
        // ……
    }
}

Character literals are enclosed in single quotes: '1'. Special characters can be escaped with backslashes. The following escape sequences are supported: \t, \b, \n, \r, \', \", \\ and \$. To encode other characters, use Unicode escape sequence syntax: '\uFF00'.

We can explicitly convert a character to an Int number:

fun decimalDigitValue(c: Char): Int {
    if (c !in '0'..'9')
        throw IllegalArgumentException("Out of range")
    return c.toInt() - '0'.toInt() // 显式转换为数字
}

When a nullable reference is needed, numbers and characters are boxed. Boxing operations do not preserve identity.


Boolean

Boolean is represented by the Boolean type, which has two values: true and false.

If a nullable reference is needed, booleans will be boxed.

Built-in boolean operations include:

|| – Short-circuit logical OR
&& – Short-circuit logical AND
! - Logical NOT

Arrays

Arrays are implemented with the Array class, and also have a size property and get and set methods. Since [] overloads the get and set methods, we can easily get or set the value at the corresponding position of the array by subscript.

There are two ways to create an array: 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) })

    //读取数组内容
    println(a[0])    // 输出结果:1
    println(b[1])    // 输出结果:2
}

As mentioned above, the [] operator represents calling the member functions get() and set().

Note: Unlike Java, arrays in Kotlin are invariant.

In addition to the Array class, there are also ByteArray, ShortArray, IntArray, which represent arrays of various types, eliminating boxing operations, and therefore more efficient. Their usage is the same as Array:

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

Strings

Like Java, String is immutable. The square bracket [] syntax can easily get a character in the string, and can also iterate through the string with a for loop:

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

Kotlin supports strings enclosed by three quotes """, supporting multi-line strings, for example:

fun main(args: Array<String>) {
    val text = """
    多行字符串
    多行字符串
    """
    println(text)   // 输出有一些前置空格
}

String can use the trimMargin() method to remove extra whitespace.

fun main(args: Array<String>) {
    val text = """
    |多行字符串
    |Example
    |多行字符串
    |Example
    """.trimMargin()
    println(text)    // 前置空格删除了
}

By default, | is used as the boundary prefix, but you can choose another character and pass it as a parameter, such as trimMargin(">").


String templates

Strings can contain template expressions, i.e., small pieces of code, which are evaluated and the results are merged into the string. Template expressions start with a dollar sign ($) and consist of a simple name:

fun main(args: Array<String>) {
    val i = 10
    val s = "i = $i" // 求值结果为 "i = 10"
    println(s)
}

Or arbitrary expressions enclosed in curly braces:

fun main(args: Array<String>) {
    val s = "example"
    val str = "$s.length is ${s.length}" // 求值结果为 "example.length is 6"
    println(str)
}

Templates are supported inside both raw strings and escaped strings. If you need to represent the literal $ character in a raw string (which does not support backslash escaping), you can use the following syntax:

fun main(args: Array<String>) {
    val price = """
    ${'$'}9.99
    """
    println(price)  // 求值结果为 $9.99
}
Other extensions