Numbers
Kotlin supports the same basic numeric types as does Java. There are four integral types:
-
Byte
(8-bit representation) -
Short
(16 bits) -
Int
(32 bits) -
Long
(64 bits)
And there are two floating-point types:
-
Float
(32 bits) -
Double
(64 bits)
These are also fairly common across other programming languages, and so it should be fairly easy to get used to them.
Number Literals
Sometimes, you will use numbers directly in your code, as literal values, such as 1234
or 3.14159
. By default, these will be an Int
and a Double
, respectively. If you want to make a literal be a Long
, add an L
suffix:
-
1234
is anInt
-
1234L
is aLong
If you want a floating-point literal to be treated as a Float
, not a Double
, append f
to the number.
If you run this snippet on the Klassbook site:
println(1234::class)
println(1234L::class)
println(3.14159::class)
println(3.14159f::class)
…you should get:
class Int
class Long
class Double
class Float
In Android Studio or IntelliJ IDEA, you will get:
class kotlin.Int
class kotlin.Long
class kotlin.Double
class kotlin.Float
Here, the ::class
syntax says “give me a reference to the Kotlin class for this object”. So, 1234::class
returns an object that tells you what class 1234
is. In this case, it is kotlin.Int
— Int
being the class, and that class being in a “package” named kotlin
. We will talk more about packages in an upcoming chapter, so just ignore that part for now.
For longer numbers, if you like, you can use underscores for the “thousands separator”. So this:
println(1_234)
gives you:
1234
Technically, those underscores can go anywhere, so 1_2_3_4
is also perfectly valid.
For integral types, the default representation is decimal format. You can define literals in hexadecimal by using an 0x
prefix (0xFFA4C639
). You can also define binary literals by using an 0b
prefix (0b10110100
).
(and for those of you wondering about octal support, like Java has… it is the 21st Century, and nobody uses octal anymore)
Mathematical Expressions
Your basic mathematical operators are available in Kotlin as they are in most other programming languages:
-
+
for addition -
-
for subtraction -
*
for multiplication -
/
for division -
%
for the remainder after division (“modulo”)
Parentheses can be used for grouping to offer manual control over the order of operations. The default order of precedence puts multiplicative operations (*
, /
, %
) higher than additive operations (+
, -
).
So:
println(1+2*3)
println((1+2)*3)
results in:
7
9
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.