Kotlinはマルチプラットフォームアプリケーション向けの静的型付け言語です。例は独立した断片であり、アプリケーション固有の型や代替の宣言をまとめた単一のコンパイル可能なファイルではありません。
変数
可変性
var mutableString: String = "Adam"
val immutableString: String = "Adam"
val inferredString = "Adam"
文字列
val name = "Adam"
val greeting = "Hello, " + name
val greetingTemplate = "Hello, $name"
val interpolated = "Hello, ${name.uppercase()}"
数値
val intNum = 10
val doubleNum = 10.0
val longNum = 10L
val floatNum = 10.0F
真偽値
val trueBoolean = true
val falseBoolean = false
val andCondition = trueBoolean && falseBoolean
val orCondition = trueBoolean || falseBoolean
コンパニオンオブジェクトのプロパティ
class Person {
companion object {
val NAME_KEY = "name_key"
}
}
val key = Person.NAME_KEY
null 安全性
null 許容プロパティ
// val cannotBeNull: String = null // Invalid
val canBeNull: String? = null // Valid
// val cannotBeNull: Int = null // Invalid
val canBeNull: Int? = null // Valid
null チェック
val name: String? = "Adam"
if (name != null && name.length > 0) {
print("String length is ${name.length}")
} else {
print("String is empty.")
}
安全呼び出し
val nullableStringLength: Int? = nullableString?.length
val nullableDepartmentHead: String? = person?.department?.head?.name
Elvis 演算子
val nonNullStringLength: Int = nullableString?.length ?: 0
val nonNullDepartmentHead: String = person?.department?.head?.name ?: ""
val nonNullDepartmentHead: String = person?.department?.head?.name.orEmpty()
安全なキャスト
// Will not throw ClassCastException
val nullableCar: Car? = (input as? Car)
コレクション
コレクションの作成
val numArray = arrayOf(1, 2, 3)
val numList = listOf(1, 2, 3)
val mutableNumList = mutableListOf(1, 2, 3)
アクセス
val firstItem = numList[0]
val firstItem = numList.first()
val firstItem = numList.firstOrNull()
マップ
val faceCards = mutableMapOf("Jack" to 11, "Queen" to 12, "King" to 13)
val jackValue = faceCards["Jack"] // 11
faceCards["Ace"] = 1
可変性
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()
反復
for (item in myList) {
print(item)
}
myList.forEach {
print(it)
}
myList.forEachIndexed { index, item ->
print("Item at $index is: $item")
}
フィルターと検索
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 は、引数が 1 つのラムダ式で使われる暗黙のパラメーター名です。 it.
関数
パラメーターと戻り値の型
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}"
高階関数
fun callbackIfTrue(condition: Boolean, callback: () -> Unit) {
if (condition) {
callback()
}
}
callbackIfTrue(someBoolean) {
print("Condition was true")
}
拡張関数
fun Int.timesTwo(): Int {
return this * 2
}
val four = 2.timesTwo()
デフォルトパラメーター
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,")
名前付き引数
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")
コンパニオンオブジェクトの関数
class Fragment(val args: Bundle) {
companion object {
fun newInstance(args: Bundle): Fragment {
return Fragment(args)
}
}
}
val fragment = Fragment.newInstance(args)
クラス
プライマリコンストラクター
class Person(val name: String, val age: Int)
val adam = Person("Adam", 100)
セカンダリコンストラクター
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)
継承とインターフェース
open class Vehicle
class Car : Vehicle()
interface Runner {
fun run()
}
class Machine : Runner {
override fun run() {
// ...
}
}
制御フロー
if 文
if (someBoolean) {
doThing()
} else {
doOtherThing()
}
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
when 式
when (direction) {
NORTH -> {
print("North")
}
SOUTH -> print("South")
EAST, WEST -> print("East or West")
"N/A" -> print("Unavailable")
else -> print("Invalid Direction")
}
while ループ
while (x > 0) {
x--
}
do {
x--
} while (x > 0)
分解宣言
オブジェクトとリスト
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
componentN 関数
class Person(val name: String, val age: Int) {
operator fun component1(): String {
return name
}
operator fun component2(): Int {
return age
}
}
参考資料
- 変数の定義 (kotlinlang.org)
- 文字列 API (kotlinlang.org)
- 文字列テンプレート (kotlinlang.org)
- 基本型 (kotlinlang.org)
- コンパニオンオブジェクト (kotlinlang.org)
- null 安全性 (kotlinlang.org)
- コレクションの概要 (kotlinlang.org)
- コレクション API (kotlinlang.org)
- 関数 (kotlinlang.org)
- クラス (kotlinlang.org)
- 分解宣言 (kotlinlang.org)
読み取り専用のコレクションインターフェースは、深い不変性を保証しません。first() はコレクションが空、または一致する要素がない場合に例外を送出し、firstOrNull() は代わりに null を返します。Android Bundle の例には Android SDK が必要です。