Kotlin Data Types
Basic Data Types
The basic forms are as follows.
var a: Boolean = true // Logical value (true, false)
var b: Byte = 123 // 8-bit integer (-128 ~ 127)
var c: Short = 123 // 16-bit integer (-32768 ~ 32767)
var d: Int = 123 // 32-bit integer (-2 31 ~ 2 31 -1)
var e: Long = 123L // 64-bit integer (-2 63 ~ 2 63 -1)
var f: Float = 12.3F // 32-bit floating point
var g: Double = 12.3 // 64-bit floating point
var h: Char = 'A' // Character (one character)
var i: String= "ABC" // String
Boolean
A Boolean is represented as true or false.
var b1: Boolean = true
var b2: Boolean = false
Numbers (Byte, Short, Int, Long, Float, Double)
Numbers are specified as follows. Octal notation (0o) is not supported. Underscores (_) are ignored.
123 Decimal (Int)
123L Decimal (Long)
0x0F Hexadecimal
0b10111100 Binary
123.4 Real number (Double)
1.23e2 Real number (Double)
123.4f Real number (Float)
1.23e2 Real number (Float)
12_345_678 Digit separator
Char
Characters are enclosed in single quotes.
'A'
The following escape sequences can be used.
\t // Tab (TAB)
\b // Backspace (BS)
\n // Line feed (LF)
\r // Carriage return (CR)
\' // Single quote (')
\" // Double quote (")
\\ // Backslash (\)
\$ // Dollar sign ($)
\uFF00 // Unicode character
String
Strings must be enclosed in double quotes ("). The escape sequences above can also be used.
"ABC"
In strings, $ and ${...} can be used to write variables or expressions.
println("$a + $b = ${add(a, b)}")
Multiline strings can be represented with triple-quoted literals such as """...""". Line breaks and backslashes are treated as normal characters.
println("""\ is a backslash""")
println("""This is Korea.
That is America.""")
Any Type
Any represents all types.
fun foo(arg: Any?) {
when (arg) {
is Int -> println("Int: $arg")
is Char -> println("Char: $arg")
is String -> println("String: $arg")
}
}
Type Conversion
The following type conversions are available.
123.toString() // Convert Int to String
"123".toInt() // Convert String to Int
"3.14".toInt() // Convert String to Int (null if conversion is not possible)
1.23.toInt() // Convert Double to Int (truncate)
1.23.roundToInt() // Convert Double to Int (round)
Range
.. represents a range. in determines whether the value on the left is inside the range shown on the right.
for (i in 1..10) println(i)
1..10 has the same meaning as 1.rangeTo(10).
for (i in 1..10) println(i)
for (i in 1.rangeTo(10)) println(i)
It can be used in if and while statements.
if (n in 1..10) println("OK")
Use !in to check that a value is not within a range.
if (n !in 1..10) println("Out of range.")
downTo creates a decreasing range. step can specify the increment amount.
for (i in 10 downTo 1 step 2) println(i)
It can also be used with characters (Char), strings (String), real numbers (Double), and more, in addition to Int.
if ('b' in 'a'..'z') println("OK")
if ("gz" in "aa".."zz") println("OK")
if (1.23 in 0.00..9.99) println("OK")
RangeTutorial.kt
fun main(args: Array<String>) {
println("==== if num1 in 4...8 ====")
val num1 = 5
if (num1 in 4..8) {
println("$num1 in 4~8")
}
println("======= if num2 !in 4...8 =======")
val num2 = 0;
if (num2 !in 4..8) {
println("$num2 not in 4~8")
}
println("========= for i in 1..7 =========")
for (i in 1..7) {
print("$i ")
}
println()
println("====== for i in 1 until 7 ======")
for (i in 1 until 7) {
print("$i ")
}
println()
println("====== for i in downTo 1 =======")
for (i in 7 downTo 1) {
print("$i ")
}
println()
println("====== for i in 1..7 step 2 ======")
for (i in 1..7 step 2) {
print("$i ")
}
}
==== if num1 in 4...8 ====
5 in 4~8
======= if num2 !in 4...8 =======
0 not in 4~8
========= for i in 1..7 =========
1 2 3 4 5 6 7
====== for i in 1 until 7 ======
1 2 3 4 5 6
====== for i in downTo 1 =======
7 6 5 4 3 2 1
====== for i in 1..7 step 2 ======
1 3 5 7
A range is a numeric range. For example, 1..5 represents the range from 1 to 5.
When a range expression is used with in in a conditional statement, it checks whether a number exists within that range.
If there is a statement such as if(number in 1..7), it is true when the value of number is between 1 and 7.
Putting an exclamation mark (!) before in reverses the operation. In other words, if(number !in 1..7) is true when number is not between 1 and 7.
When used in a for statement, it can retrieve the numeric range one value at a time. There are also until, downTo, and step.
until, as in 1 until 7, represents 1 through 6, before 7.
downTo can retrieve consecutive values decreasing from a larger number to a smaller number. Writing 7..1 causes an error.
step can specify the increment amount.
Checking Data Types (is, !is)
is is true when the data type on the left matches the data type on the right, and !is is true when it does not match. An instance of a subclass matches its parent class.
println("ABC" is String) // true
println("ABC" !is String) // false
open class ClassA() {}
class ClassB(): ClassA() {}
var a = ClassA()
var b = ClassB()
println(a is ClassA) // true
println(a is ClassB) // false
println(b is ClassA) // true
println(b is ClassB) // true
It can be checked using when.
fun foo(a: Any) {
when (a) {
is String -> println("String")
is Char -> println("Char")
else -> println("Unknown")
}
}
Type Alias
You can attach an alias to a type using typealias.
typealias Meter = Int
typealias Killometer = Int
Cast (as, as?)
as is used to cast a type. In the following example, variable a, which is not of type String, is converted (cast) to String and assigned to s. If it cannot be cast, an exception occurs.
var s : String = a as String
You can use as to cast a superclass to a subclass.
open class ClassA(val name: String) {}
class ClassB(name: String): ClassA(name) {}
var obj1: ClassA = ClassB("Yamada")
var obj2: ClassB = obj1 as ClassB
If the cast source is a nullable type, use as? instead of as.
var n1: Short? = 123
var n2: Int? = n1 as? Int?
Dynamic Type
Kotlin is basically a statically typed language, but when compiling to JavaScript, you can use dynamic for dynamic typing.
var a : dynamic
a = 123 // Assign a number
a = "ABC" // Assign a string