====== コードサンプル ======
===== Hello World! =====
fun main(){
println("hello world")
}
↓
hello world
===== クリックイベント =====
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val but = findViewById(R.id.button) as Button
but.setOnClickListener {
Toast.makeText(this, "テストメッセージです", Toast.LENGTH_SHORT).show()
}
}
}
===== ifの書き方 =====
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
↓同じ
fun main() {
println("max of 0 and 42 is ${maxOf(0, 42)}")
}
===== indices =====
val list = listOf("a", "b", "c")
println(list.lastIndex)
println(list.indices)
↓
2
0..2
===== for while =====
fun main() {
val items = listOf("apple", "banana", "kiwifruit")
for (index in items.indices) {
println("item at $index is ${items[index]}")
}
for (item in items) {
println(item)
}
var index = 0
while (index < items.size) {
println("item at $index is ${items[index]}")
index++
}
↓
item at 0 is apple
item at 1 is banana
item at 2 is kiwifruit
apple
banana
kiwifruit
item at 0 is apple
item at 1 is banana
item at 2 is kiwifruit
}
↓
item at 0 is apple
item at 1 is banana
item at 2 is kiwifruit
apple
banana
kiwifruit
fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
fun main() {
println(describe(1))
println(describe("Hello"))
println(describe(1000L))
println(describe(2))
println(describe("other"))
↓
One
Greeting
Long
Not a string
Unknown
}
===== ラムダ式 フィルター マップコレクション =====
val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.toUpperCase() }
.forEach { println(it) }
↓
APPLE
AVOCADO
===== Getter/Setter =====
自動でGetter Setter が作られる
class Data(var param: Int){
}
fun main() {
val data = Data(5)
println(data.param) // called getter
data.param = 1 // called setter
println(data.param) // called getter
}
↓
5
1
Getter Setter をカスタマイズする場合
class Animal(){
var name:String = ""
var hello:String
get(){
return name
}
set(value){
name="${value} Chan"
}
}
fun main() {
val cat = Animal()
cat.hello = "HaNa"
println(cat.name) // called getter
}
↓
HaNa Chan
===== list =====
[[https://qiita.com/kiririnyo/items/aee905225902d096f7c0|Kotlin の Collection まとめ ~List編~]]
[[https://qiita.com/opengl-8080/items/36351dca891b6d9c9687|Kotlin のコレクション使い方メモ]]
不変のリストは listOf
可変のリストは mutableListOf
文字列の結合joinToString
fun joinOptions(options: Collection) = options.joinToString(prefix = "[", postfix = "]")
fun main() {
val list = listOf("t", "e", "s", "t")
println(joinOptions(list))
}
↓
[t, e, s, t]