Kotlin勉強しながらまとめてみています。進める
内容 | Swift | Kotlin |
---|---|---|
定数 | let | val |
変数 | var | var |
文字列内の変数 | "I have \(number) apples" | "I have ${number} apples" |
配列 | var arr = ["A", "B", "C"] | var arr = array("A", "B", "C") |
ディクショナリ | var dic = ["key":"value"] | var dic = hashMapOf("key" to "value" ) |
Optional Value | var optionString: String? = "Hello" if let str= optionalString {} |
var optionString: String? = "Hello" if (optionalString != null) {} |
三項演算子 | var max = (a>b)?a:b | var max = if(a>b) a else b |
for | for item in list {} | for (item in list) {} |
条件分岐(複数) | switch (obj) { case 1: println("one") default: break } |
when(obj) { 1 -> print("one") else -> ... } |
範囲(range) | for i in 0..3 {} | for (i in (0..3)) {} |
関数宣言 | func | fun |
関数の返すデータ | func()-> DataType | func(): DataType |
関数内の関数 | func A() { func B() {} B() } |
fun A() { fun B() {} B() } |
関数のオブジェクト | func A (list: [Int], condition: Int -> Bool) -> Bool {} func B(number: Int) -> Bool {} A(array, B) |
fun hasAny (list: Array, condition: (Int) -> Boolean) : Boolean {} val B:(Int) -> Boolean{} A(array, B) |
匿名の関数 | numbers.map({ (number: Int) -> Int in let result = 3*number return result }) |
numbers.map({ val result = 3*it result }) |
簡単なクラス | class A { func simpleDescription() -> String { return "" } } var A = A() A.simpleDescription() |
class A { fun simpleDescription() : string { return "" } } var A = A() A.simpleDescription() |
イニシャライザ | class A { init(name: String ) {...} } |
class A (var name: String) {...} |