Kotlin basic data type


Release date:2023-09-22 Update date:2023-10-13 Editor:admin View counts:332

Label:

Kotlin basic data type

Kotlin basic numeric types of Byte , Short , Int , Long , Float , Double . Unlike Java, the character is not a numeric type, but a separate data type.

Types

Bit width

Double

64

Float

32

Long

64

Int

32

Short

16

Byte

8

Literal constant

Here are all types of literal constants:

  • Decimal system: 123

  • The long integer ends with an uppercase L: 123L

  • Hexadecimal begins with 0x: 0x0F

  • Base 2 begins with 0b: 0b00001011

  • Note: octal is not supported

Kotlin floating-point values represented by traditional symbols are alsosupported:

  • Doubles default writing method: 123.5, 123.5e10

  • Floats use 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

Compare two numbers

Kotlin has no basic data types, only encapsulated numeric types, and for every variable you define, in fact Kotlin it encapsulates an object for you to ensure that there is no null pointer. The number type is the same, so when comparing two numbers, there is a difference between comparing the data size and comparing whether the two objects are the same.

In Kotlin , three equal signs === represents the address of the comparison object, two == indicates that the sizes of two values are compared.

fun main(args: Array<String>) {
    val a: Int = 10000
    println(a === a) // true,equal values, equal object addresses

    //After packing, two different objects were created
    val boxedA: Int? = a
    val anotherBoxedA: Int? = a

    //Although it has been boxed, the values are equal, all of which are 10000
    println(boxedA === anotherBoxedA) //  false,equal values, different object addresses
    println(boxedA == anotherBoxedA) // true,equal values
}

Type conversion

Because of 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 set the Byte type value is assigned toa Int variable.

val b: Byte = 1 // OK, the literal value is statically detected
val i: Int = b // error

We can replace toInt() method.

val b: Byte = 1 // OK, the literal value is statically detected
val i: Int = b.toInt() // OK

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

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

In some cases, automatic type conversion can be used, as long as the correctdata type can be inferred from the context and mathematical operators are overloaded accordingly. For example, the following is true:

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

Bit operator

For Int and Long type, and a series of bit operators are available, which are:

shl(bits) – Left shift (Java’s <<)
shr(bits) – Right shift (Java’s >>)
ushr(bits) – Unsigned right shift (Java’s >>>)
and(bits) – and
or(bits) – or
xor(bits) – exclusive or
inv() – reverse

Character

Unlike Java, Char in Kotlin cannot be directly manipulated with numbers, and Char must be enclosed in single quotes. For example, regular characters such as '0' and 'a' .

fun check(c: Char) {
    if (c == 1) { // Error: Incompatible types
        // ……
    }
}

The character literal value is enclosed in single quotation marks: '1' . Special characters can be escaped with a backslash. Supports these escape sequences: \n , \r , \' , \" , \\ and \\$ . Encoding other characters requires the use of Unicode escape sequence syntax: '\uFF00'

We can explicitly convert characters to Int number:

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

When nullable references are needed, numbers and characters are boxed. The boxing operation does not retain identity.

Boolean

Boolean use Boolean type, which has two values: true and false .

If needed, a null reference Boolean will be boxed.

The built-in Boolean operations are:

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

Array

Array class Array to achieve, and there is another one size attributes and get and set method, due to using the [] overloaded get and set , method, so we can easily get or set the value of the corresponding position of the array through the subscript.

There are two ways to create an array: one is to use a function arrayOf() other is to use the factory function. 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) })

    //Reading array contents
    println(a[0])    // Output result: 1
    println(b[1])    // Output result: 2
}

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

Note: unlike Java, Kotlin array in is not covariant ( invariant ).

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

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

String

Just like Java. String is immutable. Square bracket [] syntax can easily get a character in a string, or you can use the for loop to traverse:

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

Kotlin support three quotation marks """ expanded string thatsupports multiple lines of strings, such as:

fun main(args: Array<String>) {
    val text = """
    Multiline string
    Multiline String
    """
    println(text)   // Output has some leading spaces
}

String can be passed through trimMargin() method to remove excess white space.

fun main(args: Array<String>) {
    val text = """
    |Multiline string
    |Novice tutorial
    |Multiline string
    |Runoob
    """.trimMargin()
    println(text)    // The leading space has been removed
}

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 a template expression, that is, a small piece of code that evaluates and merges the result into a string. The template expression is expressed in dollars ( $ ), consisting of a simple name:

fun main(args: Array<String>) {
    val i = 10
    val s = "i = $i" // The evaluation result is' i=10 '
    println(s)
}

Or any expression expanded with curly braces:

fun main(args: Array<String>) {
    val s = "runoob"
    val str = "$s.length is ${s.length}" // The evaluation result is "runoob.length is 6"
    println(str)
}

Templates are supported internally for both native and escaped strings. If you need to represent the literal value in the native string $ character (which does not support backslash escape), you can use the following syntax:

fun main(args: Array<String>) {
    val price = """
    ${'$'}9.99
    """
    println(price)  // The evaluation result is $9.99
}

Powered by TorCMS (https://github.com/bukun/TorCMS).