Kotlin Basics
November 1, 2022
Hello World
fun main() {
println("Hello world")
}kotlin
Define/Declare Keyword
-
val: define a variable that cannot be modified -
var: define a variable that can be modified
Basic Data Type
Numbers
Integer types
-
Byte: 8 bits -
Short: 16 bits -
Int: 32 bits -
Long: 64 bits
fun main() {
var a: Byte = 8
var b: Short = 16
var c = 32
var d: Long = 64
println(a::class.simpleName)
println(b::class.java.typeName)
println(c::class.simpleName)
println(d::class.java.typeName)
}kotlin
Floating-point types
-
Float: 32 bits -
Double: 64 bits
fun main() {
var a = 32f
var b = 64.0
println(a::class.simpleName)
println(b::class.simpleName)
}kotlin
Literal constants
fun main() {
var a = 0xff
var b = 0b11
var c = 1e9
var d = 1_000_000_000
}kotlin
Unsigned Types
-
UByte -
UShort -
UInt -
ULong - ...
Array
Null Safety
? nullable types
By default, Kotlin data type is non-null types, unless you declare it as nullable types with ?.
fun main() {
var a: Int = 1
var b: Int? = null
}kotlin
Safe Calls
val a = "Kotlin"
val b: String? = null
println(b?.length)
println(a?.length)
val a: String? = null
println(if (a?.length == null) "a is null" else "a not null")
println(a?.length == null)
a?.length?.dec()?.inc()
val listWithNulls: List<String?> = listOf("Kotlin", null)
for (item in listWithNulls) {
item?.let { println(it) }
}
kotlin
Elvis Operator
-
${nullable variable} ?: ${otherwise value}:
i.e.
val l = b?.length ?: -1
it equals to:
val l: Int = if (b != null) b.length else -1
Since throw and return are expressions in Kotlin, they can also be used on the right-hand side of the Elvis operator.
fun foo(node: Node): String? {
val parent = node.getParent() ?: return null
val name = node.getName() ?: throw IllegalArgumentException("name expected")
}kotlin
Not Null Assertion Operator !!
-
!!: Convert any value to non-null type, and will throw NPE if the reference is null.
i.e. val l = b!!.length
Safe Cast
val aInt: Int? = a as? Int: Return null instead of throwing ClassCastException when casting objects fail.
Collections of a nullable type
val nullableList: List<Int?> = listOf(1, 2, null, 4)
val intList: List<Int> = nullableList.filterNotNull()kotlin
Collections
todo...