Data Types

Data Types

Basic Data types

  1. Numbers
  1. Boolean
  1. Characters
  1. Strings
  1. Arrays

⇒ Numbers

  • Kotlin provides a set of built-in types that represent numbers.

⇒ Integers numbers

  • there are four types with different sizes and, hence, value ranges:
Type
Size (bits)
Min value
Max value
Byte
8
-128
127
Short
16
-32768
32767
Int
32
-2,147,483,648 or ( -2^31)
2,147,483,647 or ( 2^31 -1)
Long
64
-9,223,372,036,854,775,808 or ( -2^63)
9,223,372,036,854,775,807 or ( 2^63 -1)
  • When you initialize a variable with no explicit type specification, the compiler automatically infers the type with the smallest range enough to represent the value.
  • If it is not exceeding the range of Int, the type is Int. If it exceeds, the type is Long.
  • To specify the Long value explicitly, append the suffix L to the value. Explicit type specification triggers the compiler to check the value not to exceed the range of the specified type.
val oneLong = 1L // Long

⇒ Floating-Point Numbers

  • For real numbers, Kotlin provides floating-point types Float and Double
Type
Size (bits)
Significant bits
Exponent bits
Decimal digits
Float
32
24
8
6-7
Double
64
53
11
15-16
  • You can initialize Double and Float variables with numbers having a fractional part.
  • It's separated from the integer part by a period ( . )
val PI = 3.14 //Double
  • To explicitly specify the Float type for a value, add the suffix f or F , If such a value contains more than 6-7 decimal digits, it will be rounded:
val e = 2.7182818284 // Double val eFloat = 2.7182818284f // Float, actual value is 2.7182817
Note:
Unlike some other languages, there are no implicit widening conversions for numbers in Kotlin. For example, a function with a Double parameter can be called only on Double values, but not Float, Int, or other numeric values:

⇒ Boolean

  • The type Boolean represents boolean objects that can have two values: true , false.
  • Built-in operations on booleans include:
      1. || - disjuction ( Logical OR )
      1. && - Conjuction (Logical AND )
      1. ! - Negation ( Logical NOT )
fun main() { val myTrue: Boolean = true val myFalse: Boolean = false val boolNull: Boolean? = null println(myTrue || myFalse) println(myTrue && myFalse) println(!myTrue) }
 

⇒ Characters

  • Characters are represented by the type Char.
  • Character literals go in single quotes: ' 1 '
  • Special characters start from an escaping backslash \.
  • The following escape sequences are supported:
      1. \t - tab
      1. \b - backspace
      1. \n - new line (LF)
      1. \r - carriage return (CR)
      1. \’ - Single quotation mark
      1. \” - Double quotation mark
      1. \\ - backslash
      1. \$ - Dollar sign