ComponentN Functions
class Person(val name: String, val age: Int) {
operator fun component1(): String {
return name
}
operator fun component2(): Int {
return age
}
}
References
- Defining Variables (kotlinlang.org)
- Strings Documentation (kotlinlang.org)
- String Templates (kotlinlang.org)
- Basic Types (kotlinlang.org)
- Companion Objects (kotlinlang.org)
- Null Safety (kotlinlang.org)
- Collections Overview (kotlinlang.org)
- Collections Documentation (kotlinlang.org)
- Functions Documentation (kotlinlang.org)
- Classes Documentation (kotlinlang.org)
- Destructuring Declarations (kotlinlang.org) ### Objects & Lists
val person = Person("Adam", 100)
val (name, age) = person
val pair = Pair(1, 2)
val (first, second) = pair
val coordinates = arrayOf(1, 2, 3)
val (x, y, z) = coordinates
While Loops
while (x > 0) {
x--
}
do {
x--
} while (x > 0)
Destructuring Declarations
{: .-two-column}
When Statements
when (direction) {
NORTH -> {
print("North")
}
SOUTH -> print("South")
EAST, WEST -> print("East or West")
"N/A" -> print("Unavailable")
else -> print("Invalid Direction")
}
For Loops
for (i in 0..10) { } // 1 - 10
for (i in 0 until 10) // 1 - 9
(0..10).forEach { }
for (i in 0 until 10 step 2) // 0, 2, 4, 6, 8
If Statements
if (someBoolean) {
doThing()
} else {
doOtherThing()
}
Inheritance & Implementation
open class Vehicle
class Car : Vehicle()
interface Runner {
fun run()
}
class Machine : Runner {
override fun run() {
// ...
}
}
Control Flow
Secondary Constructors
class Person(val name: String) {
private var age: Int? = null
constructor(name: String, age: Int) : this(name) {
this.age = age
}
}
// Above can be replaced with default params
class Person(val name: String, val age: Int? = null)
Primary Constructor
class Person(val name: String, val age: Int)
val adam = Person("Adam", 100)
Static Functions
class Fragment(val args: Bundle) {
companion object {
fun newInstance(args: Bundle): Fragment {
return Fragment(args)
}
}
}
val fragment = Fragment.newInstance(args)
Top comments (0)