Читать книгу Programming Kotlin Applications - Бретт Мак-Лахлин, Brett McLaughlin - Страница 58

Numbers in Kotlin

Оглавление

Kotlin gives you four options for integers, largely varying based on range. These are shown in Table 2.1.

TABLE 2.1: Kotlin Types for Integers (Nondecimal Numbers)

TYPE SIZE (BITS) MINIMUM VALUE MAXIMUM VALUE
Byte 8 –128 127
Short 16 –32,678 32,767
Int 32 –2,147,483,648 (–231) 2,147,483,647 (231 – 1)
Long 64 –9,223,372,036,854,775,808 (–263) 9,223,372,036,854,775,807 (263 – 1)

Kotlin will largely take care of figuring out which type to use when you don't declare that type explicitly. In that case, it's going to look at the value you're assigning the variable, and make some assumptions. This is a pretty important concept called type inference, and it's something we're going to talk about in a lot more detail in Chapter 6.

If you create a variable and assign it a number that fits into Int, then Int will be used. If the number is outside the range of Int, the variable will be created as a Long :

val someInt = 20 val tooBig = 4532145678

So here, someInt will be an Int. tooBig is too big to fit into an Int so it will be a Long. You can also force a variable to be a Long by adding a capital L to the value:

val makeItLong = 42L

Kotlin gives you a couple of options for decimals, as well: two, again, based on precision and size. Those are listed in Table 2.2.

TABLE 2.2: Kotlin Types for Decimal Numbers

TYPE SIZE (BITS) SIGNIFICANT BITS EXPONENT BITS DECIMAL DIGITS
Float 32 24 8 6–7
Double 64 53 11 15–16

Assignment here works a bit unexpectedly. Decimal variables will be Double unless you tell Kotlin to use Float by using the f or F suffix:

val g = 9.8 val theyAllFloat = 9.8F

Programming Kotlin Applications

Подняться наверх