This document provides an overview of Kotlin basics including:
- Basic data types like Int, String, Boolean
- Collections like List, Set, Map
- Variables, functions, control flow
- Classes, properties, constructors
- Inheritance, interfaces
- Additional features like lambdas, extensions, coroutines
It aims to introduce fundamental Kotlin concepts and syntax in a concise manner.
53. When
when {
x in 1..10 -> print("x is in the range")
x in validNumbers -> print("x is valid")
x !in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}
54. for
for (item in collection) print(item)
for (item: String in collection) {
print(item)
}
for (i in collection.indices) {
println(collection[i])
}
for ((index, value) in collection.withIndex()) {
println("the element at $index is $value")
}
96. Classes defaults
• All non-abstract classes final
Effective Java, Item 17: Design and document for inheritance or else prohibit it.
• All properties final
• All functions final
• Inner classes static
• All members public by default
98. What is “Modules”?
• An IntelliJ IDEA module
• A Maven project
• A Gradle source set
• A set of files compiled with one invocation of the Ant Task
99. Data Classes
class Point(var x: Float, val y: Float) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as Point
return x == other.x && y == other.y
}
override fun hashCode() = 31 * x.hashCode() + y.hashCode()
override fun toString() = "Point(x=$x, y=$y)"
}
102. Data classes
• Implement equals(), hashCode()
• toString() of the form “Point(x=12.3,y=59.1)”
• Add componentN() functions corresponding to the properties in their order
of declaration
• Add copy() function
114. Inheritance
open class Point(var x: Float, val y: Float)
class Point3D : Point {
val z: Float
constructor(x: Float, y: Float, z: Float) : super(x, y) {
this.z = z
}
}
116. Interfaces
interface SampleInterface {
val prop: Int
fun bar()
fun foo()
}
class SampleClass : SampleInterface {
override val prop = 20
override fun bar() {}
override fun foo() {}
}