Kotlin est un langage à typage statique pour les applications multiplateformes. Les exemples sont des fragments indépendants ; les types applicatifs et les déclarations alternatives ne constituent pas un fichier compilable unique.
Variables
Mutabilité
var mutableString: String = "Adam"
val immutableString: String = "Adam"
val inferredString = "Adam"
Chaînes
val name = "Adam"
val greeting = "Hello, " + name
val greetingTemplate = "Hello, $name"
val interpolated = "Hello, ${name.uppercase()}"
Nombres
val intNum = 10
val doubleNum = 10.0
val longNum = 10L
val floatNum = 10.0F
Booléens
val trueBoolean = true
val falseBoolean = false
val andCondition = trueBoolean && falseBoolean
val orCondition = trueBoolean || falseBoolean
Propriétés des objets compagnons
class Person {
companion object {
val NAME_KEY = "name_key"
}
}
val key = Person.NAME_KEY
Sûreté face aux valeurs nulles
Propriétés pouvant être nulles
// val cannotBeNull: String = null // Invalid
val canBeNull: String? = null // Valid
// val cannotBeNull: Int = null // Invalid
val canBeNull: Int? = null // Valid
Tests de nullité
val name: String? = "Adam"
if (name != null && name.length > 0) {
print("String length is ${name.length}")
} else {
print("String is empty.")
}
Appels sûrs
val nullableStringLength: Int? = nullableString?.length
val nullableDepartmentHead: String? = person?.department?.head?.name
Opérateur Elvis
val nonNullStringLength: Int = nullableString?.length ?: 0
val nonNullDepartmentHead: String = person?.department?.head?.name ?: ""
val nonNullDepartmentHead: String = person?.department?.head?.name.orEmpty()
Conversions de type sûres
// Will not throw ClassCastException
val nullableCar: Car? = (input as? Car)
Collections
Créer des collections
val numArray = arrayOf(1, 2, 3)
val numList = listOf(1, 2, 3)
val mutableNumList = mutableListOf(1, 2, 3)
Accès
val firstItem = numList[0]
val firstItem = numList.first()
val firstItem = numList.firstOrNull()
Dictionnaires
val faceCards = mutableMapOf("Jack" to 11, "Queen" to 12, "King" to 13)
val jackValue = faceCards["Jack"] // 11
faceCards["Ace"] = 1
Mutabilité
val immutableList = listOf(1, 2, 3)
val mutableList = immutableList.toMutableList()
val immutableMap = mapOf("Jack" to 11, "Queen" to 12, "King" to 13)
val mutableMap = immutableMap.toMutableMap()
Itération
for (item in myList) {
print(item)
}
myList.forEach {
print(it)
}
myList.forEachIndexed { index, item ->
print("Item at $index is: $item")
}
Filtrer et rechercher
val evenNumbers = numList.filter { it % 2 == 0 }
val containsEven = numList.any { it % 2 == 0 }
val containsNoEvens = numList.none { it % 2 == 0 }
val containsNoEvens = numList.all { it % 2 == 1 }
val firstEvenNumber: Int = numList.first { it % 2 == 0 }
val firstEvenOrNull: Int? = numList.firstOrNull { it % 2 == 0 }
val fullMenu = objList.map { "${it.name} - $${it.detail}" }
it est le nom implicite de l’unique paramètre d’une expression lambda. it.
Fonctions
Paramètres et types de retour
fun printName() {
print("Adam")
}
fun printName(person: Person) {
print(person.name)
}
fun getGreeting(person: Person): String {
return "Hello, ${person.name}"
}
fun getGreeting(person: Person): String = "Hello, ${person.name}"
fun getGreeting(person: Person) = "Hello, ${person.name}"
Fonctions d’ordre supérieur
fun callbackIfTrue(condition: Boolean, callback: () -> Unit) {
if (condition) {
callback()
}
}
callbackIfTrue(someBoolean) {
print("Condition was true")
}
Fonctions d’extension
fun Int.timesTwo(): Int {
return this * 2
}
val four = 2.timesTwo()
Paramètres par défaut
fun getGreeting(person: Person, intro: String = "Hello,"): String {
return "$intro ${person.name}"
}
// Returns "Hello, Adam"
val hello = getGreeting(Person("Adam"))
// Returns "Welcome, Adam"
val welcome = getGreeting(Person("Adam"), "Welcome,")
Arguments nommés
class Person(val name: String = "", age: Int = 0)
// All valid
val person = Person()
val person = Person("Adam", 100)
val person = Person(name = "Adam", age = 100)
val person = Person(age = 100)
val person = Person(age = 100, name = "Adam")
Fonctions des objets compagnons
class Fragment(val args: Bundle) {
companion object {
fun newInstance(args: Bundle): Fragment {
return Fragment(args)
}
}
}
val fragment = Fragment.newInstance(args)
Classes
Constructeurs primaires
class Person(val name: String, val age: Int)
val adam = Person("Adam", 100)
Constructeurs secondaires
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)
Héritage et interfaces
open class Vehicle
class Car : Vehicle()
interface Runner {
fun run()
}
class Machine : Runner {
override fun run() {
// ...
}
}
Contrôle de flux
Instructions if
if (someBoolean) {
doThing()
} else {
doOtherThing()
}
Boucles for
for (i in 0..10) { } // 0 - 10
for (i in 0 until 10) { } // 0 - 9
(0..10).forEach { }
for (i in 0 until 10 step 2) { } // 0, 2, 4, 6, 8
Expressions when
when (direction) {
NORTH -> {
print("North")
}
SOUTH -> print("South")
EAST, WEST -> print("East or West")
"N/A" -> print("Unavailable")
else -> print("Invalid Direction")
}
Boucles while
while (x > 0) {
x--
}
do {
x--
} while (x > 0)
Déclarations de déstructuration
Objets et listes
data class Person(val name: String, val age: Int)
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
Fonctions componentN
class Person(val name: String, val age: Int) {
operator fun component1(): String {
return name
}
operator fun component2(): Int {
return age
}
}
Références
- Définir des variables (kotlinlang.org)
- API des chaînes (kotlinlang.org)
- Modèles de chaînes (kotlinlang.org)
- Types de base (kotlinlang.org)
- Objets compagnons (kotlinlang.org)
- Sûreté face aux valeurs nulles (kotlinlang.org)
- Présentation des collections (kotlinlang.org)
- API des collections (kotlinlang.org)
- Fonctions (kotlinlang.org)
- Classes (kotlinlang.org)
- Déclarations de déstructuration (kotlinlang.org)
Les interfaces de collections en lecture seule ne garantissent pas une immutabilité profonde. first() lève une exception si la collection est vide ou sans élément correspondant ; firstOrNull() renvoie null. Les exemples Android Bundle nécessitent le SDK Android.