Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin Basic Data Types

Kotlin Basic Data Types

Kotlin is a statically typed language; a variable's type is determined at declaration, and the compiler checks type correctness at compile time.

Kotlin categorizes data into numeric types (Byte, Short, Int, Long, Float, Double), the Boolean type, the Char type, the String type, and array types, among others.

This article introduces the value ranges, literal syntax, and conversion rules of these basic types, which form the foundation for learning functions, collections, and object-oriented programming later.


Numeric Types and Bit Widths

Kotlin's numeric types are largely the same as Java's, with one important difference: Kotlin's Char is not a numeric type and cannot directly take part in numeric operations.

The table below lists the bit widths and value ranges of the six numeric types.

Type Bit width Value range Description
Byte 8 -128 ~ 127 The smallest integer type
Short 16 -32768 ~ 32767 Less commonly used
Int 32 -2147483648 ~ 2147483647 The default integer type
Long 64 -9223372036854775808 ~ 9223372036854775807 Literals require an L suffix
Float 32 Approximately ±3.4×1038 Single precision, 6~7 significant digits, add an f suffix to literals
Double 64 Approximately ±1.8×10308 Double precision, 15~16 significant digits, the default floating-point type

On the JVM, non-null Int, Long, and Double are represented directly using Java's int, long, and double primitive types, with no extra object overhead.

Only when you put them into generics or declare them as nullable types (such as Int?) does boxing occur, turning them into objects like Integer and Long.

Bit Width and Overflow

Each integer type has a fixed bit width; when a computation result exceeds the range, overflow occurs instead of an exception being thrown.

The following example demonstrates the boundary behavior of Int.

Example

fun main

(

)

{

    val max

=

Int.

MAX_VALUE

     

// The maximum value of Int

    println

(

max

)

               

// 2147483647

    println

(

max

1

)

           

// -2147483648, wraps around to the minimum value after overflow

    val min

=

Int.

MIN_VALUE

     

// The minimum value of Int

    println

(

min

)

               

// -2147483648

    println

(

min

1

)

           

// 2147483647, overflow in the other direction

   

// Use Long when you need a larger range; remember to convert Int to Long before adding

    val big

=

Int.

MAX_VALUE

.

toLong

(

)

1

    println

(

big

)

               

// 2147483648

}



2147483647

-2147483648

-2147483648

2147483647

2147483648

Note:Kotlin does not report an error for integer overflow, which is consistent with Java's behavior. For sensitive calculations involving money or timestamps, you should proactively check ranges or switch to Long or BigInteger.


Literal Constants

Literal constants are values written directly in code, such as 123, 0x0F, and 3.14.

Kotlin supports three integer notations, decimal, hexadecimal, and binary, but not octal, which is one difference from C and Java.

The table below summarizes the syntax for various literals.

Syntax Example Description
Decimal 123 Inferred as Int by default
Hexadecimal 0x0F 0x prefix, uppercase or lowercase
Binary 0b00001011 0b prefix
Octal None Kotlin does not support octal literals
Long 123L L suffix; literals exceeding the Int range are also inferred as Long
Double 123.5、123.5e10 The default type of floating-point literals
Float 123.5f f or F suffix
Underscore separators 1_000_000 Only for improving readability; the compiler ignores underscores

Underscores can only go between digits, not at the beginning or end, and not adjacent to a decimal point.

The following example covers these notations.

Example

fun main

(

)

{

    val dec

=

123

                 

// Decimal

    val hex

=

0x0F                

// Hexadecimal, equal to 15 in decimal

    val bin

=

0b00001011          

// Binary, equal to 11 in decimal

    val

long

=

123L                

// Long literal

    val oneMillion

=

1

_000_000    

// Underscore separators for readability

   

// Hexadecimal and binary can also use underscores for grouping

    val hexBytes

=

0xFF_EC_DE

    val bytes

=

0b1101_0010

   

// Floating-point literals default to Double; add an f suffix for Float

    val pi

=

3.14

    val piFloat

=

3.14f

    val sci

=

123.5e10            

// Scientific notation, equal to 1.235E12

    println

(

dec

)

    println

(

hex

)

    println

(

bin

)

    println

(

long

)

    println

(

oneMillion

)

    println

(

hexBytes

)

    println

(

bytes

)

    println

(

pi

)

    println

(

piFloat

)

    println

(

sci

)

}



123

15

11

123

1000000

16772318

210

3.14

3.14

1.235E12

Note:If you write an octal-style value like 0755, Kotlin treats it as the decimal number 755, no error is raised, and you won't get an octal result, so be especially careful.


No Implicit Conversion Between Numeric Types

This is a key difference between Kotlin and Java/C: smaller numeric types are not automatically converted to larger ones.

Even a seemingly safe conversion such as Byte to Int requires an explicit call to a conversion function.

This design avoids silent data loss, at the cost of some extra conversion calls in the code.

Example

fun main

(

)

{

    val b

:

Byte

=

1

   

// val i: Int = b // Compile error: Kotlin does not implicitly convert Byte to Int

    val i

:

Int

=

b.

toInt

(

)

 

// You must call a conversion function explicitly

    println

(

i

)

             

// 1

   

// Literals are an exception: the compiler can confirm at compile time that 100 is within the Byte range

    val b2

:

Byte

=

100

    println

(

b2

)

             

// 100

   

// Arithmetic can mix types; the result type is determined by the operands

    val l

=

1L

3

         

// Long + Int yields Long

    println

(

l

)

             

// 4

}



1

100

4

A literal can be assigned directly to a smaller type because the compiler can determine at compile time that its value is within range.

But when assigning a variable to another type, the compiler cannot guarantee the runtime value won't overflow, so it always reports an error.

Explicit type conversion

Every numeric type provides a full set of conversion functions whose names begin with to.

The table below lists all conversion functions on Int.

function Return Type Description
toByte() Byte Truncates bit-wise when out of the Byte range
toShort() Short Truncates bit-wise when out of the Short range
toInt() Int Returns itself
toLong() Long Safe widening
toFloat() Float Large values may lose precision
toDouble() Double Large values may lose precision
toChar() Char Converts a code point to the corresponding character
toUByte() UByte Since Kotlin 1.5
toUShort() UShort Since Kotlin 1.5
toUInt() UInt Since Kotlin 1.5
toULong() ULong Since Kotlin 1.5

Other numeric types have these functions too; the one returning its own type simply returns the value unchanged.

The following example demonstrates several typical conversion results.

Example

fun main

(

)

{

    val i

:

Int

=

65

    println

(

i.

toByte

(

)

)

     

// 65

    println

(

i.

toShort

(

)

)

   

// 65

    println

(

i.

toLong

(

)

)

     

// 65

    println

(

i.

toFloat

(

)

)

   

// 65.0

    println

(

i.

toDouble

(

)

)

   

// 65.0

    println

(

i.

toChar

(

)

)

     

// A; 65 is the code point of the character A

   

// Converting float to integer discards the fractional part rather than rounding

    val d

:

Double

=

3.99

    println

(

d.

toInt

(

)

)

     

// 3

    println

(

d.

toLong

(

)

)

     

// 3

   

// Truncates bit-wise when out of the target type's range

    val big

:

Int

=

300

    println

(

big.

toByte

(

)

)

   

// 44; 300 is out of the Byte range, keeping the low 8 bits

}



65

65

65

65.0

65.0

A

3

3

44

Note:Converting float to integer simply truncates the fractional part; 3.99.toInt() yields 3. For rounding, use kotlin.math.roundToInt().


Unsigned Types

Kotlin provides four unsigned integer types, UByte, UShort, UInt, and ULong, which can represent only zero and positive numbers, with twice the positive range of their signed counterparts.

These four types were introduced in Kotlin 1.3 (experimental) and became stable in Kotlin 1.5.

The accompanying unsigned arrays such as UByteArray are still a Beta feature and require the @ExperimentalUnsignedTypes annotation when used.

Type Bit width Value range
UByte 8 0 ~ 255
UShort 16 0 ~ 65535
UInt 32 0 ~ 4294967295
ULong 64 0 ~ 18446744073709551615

Unsigned literals use the u, U, uL, and UL suffixes, and the specific type can be inferred from the expected type.

Example

fun main

(

)

{

    val u

:

UInt

=

42u          

// u suffix; with the expected type this yields UInt

    val ul

:

ULong

=

1u          

// The expected type is ULong, so 1u is also treated as ULong

    val explicit

:

ULong

=

1uL  

// uL suffix explicitly specifies ULong

    val

byte

:

UByte

=

0xFFu    

// The expected type is UByte, and 255 is within range

    val us

:

UShort

=

1u        

// The expected type is UShort

    println

(

u

)

                 

// 42

    println

(

ul

)

               

// 1

    println

(

explicit

)

         

// 1

    println

(

byte

)

             

// 255

    println

(

us

)

               

// 1

    println

(

UInt.

MAX_VALUE

)

   

// 4294967295

    println

(

UByte.

MIN_VALUE

)

   

// 0

    println

(

u

1u

)

           

// 43, unsigned arithmetic

    println

(

u.

toInt

(

)

)

         

// 42, converted back to signed Int

}



42

1

1

255

1

4294967295

0

43

42

Unsigned types are not subtypes of signed types, nor can they be implicitly converted to them; mixing them causes a direct compile error.

Use cases:Unsigned types are mainly used to represent full bit patterns, such as the 32-bit color value 0xFFCC00CCu. They are not suitable for expressing values that "cannot be negative" in business logic; collection indices should still use Int, because an empty collection's lastIndex needs to return -1.


Comparing Two Numbers

Kotlin provides two kinds of equality checks:== checks structural equality (whether values are equal),=== checks referential equality (whether it is the same object).

For values like Int, Long, and Double that are represented as primitives at runtime,=== is equivalent to ==, comparing references has no practical meaning.

To observe the difference in referential equality, you must use a boxed nullable type such as Int?.

Example

fun main

(

)

{

    val a

:

Int

=

5

    val b

:

Int

=

10

    println

(

a

==

b

)

     

// false; structural equality compares values

    println

(

a

!=

b

)

     

// true

    println

(

a

<

b

)

// true

    println

(

a

b

)

     

// false

    println

(

a

<=

b

)

     

// true

    println

(

a

=

b

)

     

// false

   

// Int is a primitive, so === degrades to be the same as ==

    val x

:

Int

=

1000

    val y

:

Int

=

1000

    println

(

x

==

y

)

     

// true

    println

(

x

===

y

)

   

// true; for primitives === is equivalent to ==

   

// To observe referential equality, you must use the boxed type Int?

    val p

:

Int

?

=

1000

    val q

:

Int

?

=

1000

    println

(

p

==

q

)

     

// true; values are equal

    println

(

p

===

q

)

   

// false; 1000 is outside the cache range, so two distinct boxed objects

    val m

:

Int

?

=

100

    val n

:

Int

?

=

100

    println

(

m

===

n

)

   

// true; hits the JVM Integer cache of -128..127

}



false

true

true

false

true

false

true

true

true

false

true

The compiler will warn:Both places above === trigger a warning, for Int Is identity equality for arguments of types 'Int' and 'Int' is deprecated, for Int? Is ... is prohibited. This code compiles and runs, but in normal business code do not use numbers with ===, whose only purpose is to determine whether two object references are identical.

Common mistake:Puts the val x: Int = 1000; val y: Int = 1000 's x === y described as false. In fact, for primitives like Int,=== The difference between == are completely equivalent, and the result is true. Only after boxing into Int? does 1000 exceed the JVM Integer cache range of -128..127, causing the two boxing operations to produce different objects.

Between different numeric types you cannot use == for comparison, because Int and Double are different types with no subtype relationship, and the compiler reports an error directly.

but <、>、<=、>= can be used across types, because the standard library provides a series of compareTo overloads for numeric types, such as Int.compareTo(other: Double).

Example

fun main

(

)

{

    val i

:

Int

=

5

    val d

:

Double

=

5.0

   

// val bad = (i == d) // Compile error: Int and Double cannot be compared directly with ==

   

// Magnitude comparison can cross types, going through the Int.compareTo(Double) overload

    println

(

i

<

d

)

// false

    println

(

i

4.9

)

         

// true

    println

(

i.

compareTo

(

d

)

)

   

// 0; returns 0 when equal

}



false

true

0

Do not confuse:Int and Double can be compared in magnitude thanks to the overloaded Int.compareTo(Double) function, not because Int is automatically converted to Double. Kotlin has no implicit type conversion.


Boolean type

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

Boolean values support short-circuit logical operations:&& represents AND,|| represents OR,! represents NOT.

Short-circuiting means that when the left side already determines the result, the right side's expression is not evaluated.

Example

fun main

(

)

{

    val t

:

Boolean

=

true

    val f

:

Boolean

=

false

    println

(

t

&&

f

)

     

// false

    println

(

t

||

f

)

     

// true

    println

(

!

t

)

         

// false

   

// You can also use the function form

    println

(

t.

and

(

f

)

)

   

// false

    println

(

t.

or

(

f

)

)

   

// true

    println

(

t.

xor

(

f

)

)

   

// true; XOR: true when the two values differ

    println

(

t.

not

(

)

)

   

// false

}



false

true

false

false

true

true

false

The following example prints the evaluation process so you can see the effect of short-circuiting directly.

Example

fun check

(

)

:

Boolean

{

    println

(

"check was called"

)

   

return

true

}

fun main

(

)

{

    val f

=

false

    println

(

f

&&

check

(

)

)

   

// false; the left side is already false, so the right side is not evaluated

    println

(

true

||

check

(

)

)

 

// true; the left side is already true, so the right side is not evaluated

    println

(

true

&&

check

(

)

)

 

// true; the right side must be evaluated

}



false

true

check 被调用

true

If you need a nullable Boolean type, Boolean?, the value will be boxed, just like nullable numeric types.


The Char Type

Characters are represented by Char, and literals must be written in single quotes, such as 'A' and '0'.

Unlike Java, Kotlin's Char is not a numeric type; it cannot be assigned directly to Int, nor compared directly with numbers.

Example

fun main

(

)

{

    val c

:

Char

=

'A'

    println

(

c

)

                 

// A

    println

(

c.

code

)

           

// 65; the Unicode code point of the character

    println

(

c

1

)

             

// B; Char + Int yields a new Char

    println

(

c

'A'

)

           

// 0; subtracting two Chars yields an Int

    println

(

'5'

.

digitToInt

(

)

)

 

// 5; converting a digit character to a number

   

// val n: Int = c // Compile error: Char cannot be assigned directly to Int

    val n

:

Int

=

c.

code

    println

(

n

)

                 

// 65

}



A

65

B

0

5

65

Special characters are escaped with a backslash; the table below lists the escape sequences supported by Kotlin.

Escape sequences Meaning
\t Tab
\b Backspace
\n Newline
\r Carriage return
' Single quote
" Double quote
\ Backslash
$ Dollar sign, to avoid being treated as a string template
\uXXXX Four-digit hexadecimal Unicode character

Example

fun main

(

)

{

    println

(

"Newline: \nsecond line"

)

       

// Prints two lines

    println

(

"Backslash: \"

)

             

// Backslash: \

    println

(

"Double quote: ""

)

             

// Double quote: "

    println

(

"Dollar sign: $"

)

           

// Dollar sign: $

    println

(

"Unicode escape: \u0041"

)

   

// Unicode escape: A

}



Newline character:

第二行

反斜杠:\

双引号:"

美元符号:$

Unicode 转义:A

Tip:Since Kotlin 1.5, use Char.code to get the code point; the old Char.toInt() is deprecated. To convert a digit character to a number, use digitToInt(); non-digit characters throw an exception.


arrays

Arrays are represented by the Array class, which has a size property and supports reading and writing elements with square brackets through operator overloading.

The two common ways to create an array are the arrayOf() and Array(size) { ... } factory functions.

Example

fun main

(

)

{

   

// arrayOf infers the type from the elements, yielding an Array

    val a

=

arrayOf

(

1

,

2

,

3

)

   

// Array(3) { ... } is a factory function: it is the index, starting from 0

    val b

=

Array

(

3

)

{

it

2

}

       

// [0, 2, 4]

    println

(

a

[

0

]

)

                     

// 1

    println

(

b

[

1

]

)

                     

// 2

    println

(

a.

size

)

                   

// 3

    println

(

b.

contentToString

(

)

)

     

// [0, 2, 4]

   

// Square brackets are equivalent to calling get and set

    a

[

0

]

=

100

    println

(

a

[

0

]

)

                     

// 100

    println

(

a.

contentToString

(

)

)

     

// [100, 2, 3]

   

// Primitive-type arrays avoid boxing and perform better

    val ints

:

IntArray

=

intArrayOf

(

1

,

2

,

3

)

    ints

[

0

]

=

ints

[

1

]

ints

[

2

]

    println

(

ints.

contentToString

(

)

)

   

// [5, 2, 3]

}



1

2

3

[0, 2, 4]

100

[100, 2, 3]

[5, 2, 3]

Besides Array, Kotlin also provides specialized arrays such as ByteArray, ShortArray, IntArray, LongArray, FloatArray, DoubleArray, and CharArray, which incur no boxing overhead.

The following example demonstrates several common ways to create arrays.

Example

fun main

(

)

{

    val zeros

=

IntArray

(

3

)

{

0

}

         

// Specify the length and an initialization function

    val squares

=

IntArray

(

5

)

{

it

it

}

 

// it is the index

    val names

=

Array

(

3

)

{

"RUNOOB"

}

     

// Every element is initialized with the same expression

    val nulls

=

arrayOfNulls

<

String

(

2

)

// All elements are null

    println

(

zeros.

contentToString

(

)

)

       

// [0, 0, 0]

    println

(

squares.

contentToString

(

)

)

     

// [0, 1, 4, 9, 16]

    println

(

names.

contentToString

(

)

)

       

// [RUNOOB, RUNOOB, RUNOOB]

    println

(

nulls.

contentToString

(

)

)

       

// [null, null]

   

// A two-dimensional array: the elements are themselves arrays

    val grid

=

Array

(

2

)

{

IntArray

(

3

)

{

0

}

}

    grid

[

1

]

[

2

]

=

9

    println

(

grid

[

1

]

.

contentToString

(

)

)

     

// [0, 0, 9]

}



[0, 0, 0]

[0, 1, 4, 9, 16]

[RUNOOB, RUNOOB, RUNOOB]

[null, null]

[0, 0, 9]

Arrays Are Not Covariant

Unlike Java, Kotlin arrays are invariant: Array is not a subtype of Array.

This is for type safety. Java allows assigning String[] to Object[], and only throws ArrayStoreException at runtime when a wrong type is written; Kotlin moves such errors forward to compile time.

Example

fun main

(

)

{

    val strings

=

arrayOf

(

"Runoob"

,

"www.runoob.com"

)

   

// val anys: Array = strings // Compile error: arrays are not covariant

   

// When you need an Array , you can only copy the elements explicitly

    val anys

:

Array

<

Any

=

Array

(

strings.

size

)

{

strings

[

it

]

}

    println

(

anys.

contentToString

(

)

)

   

// [Runoob, www.runoob.com]

}



[Runoob, www.runoob.com]

Arrays have a fixed length and cannot add or remove elements after creation. When you need a dynamic length, use collection types such as List and MutableList; see Chapter 28, "Kotlin Collections》。


Common questions

Below are the questions beginners most often encounter when using basic data types.

Why is val b: Byte = 100 allowed, but val i: Int = b is not

100 is a literal, and the compiler can confirm at compile time that it falls within the Byte range, so direct assignment is allowed.

b is a variable whose runtime value could theoretically exceed the target type's range; the compiler cannot prove it safe, so an explicit conversion is required.

Which should you choose, Float or Double

Use Double by default. It has higher precision and is also the default type for Kotlin floating-point literals.

Use Float only when you clearly need to save memory or are working with an API that accepts only Float.

When should you use Long

Values that easily exceed 2.1 billion, such as millisecond timestamps, database auto-increment IDs, and file sizes, should all use Long.

Don't forget the L suffix when writing a Long literal, or it will be treated as an Int and cause an error.

Array What's the difference with IntArray

IntArray is backed by Java's int[] and is not boxed, so it performs better.

Array stores boxed Integer objects and can hold null (that is, Array)。

For performance-sensitive scenarios prefer IntArray; use Array when you need generics or nullable elements.

Why can't Char be compared with Int

Because Kotlin defines Char as a distinct type rather than a numeric type.

When you need to compare code points, first use .code to get an Int and then compare; to convert a digit character to a number, use digitToInt()。