Skip to content

Instantly share code, notes, and snippets.

@ayakix
Last active December 8, 2017 06:14
Show Gist options
  • Save ayakix/92b0e62d1b190a2e2f6b8de04730708a to your computer and use it in GitHub Desktop.
Save ayakix/92b0e62d1b190a2e2f6b8de04730708a to your computer and use it in GitHub Desktop.
Cheat sheet for Kotlin

val, var

if let

val name: String? = "John Doe"

name?.let {
   print("Name: ${it}")
}

hoge?.let {
    it.action()
} ?: run {
    // nullの場合
}

guard

var hoge = hoge ?: return

lateinit

private lateinit var message:String

onCreate() {
  message = "hello"
}

Callback

func action(completion: (() -> Unit)? = null)
completion?.invoke()

3項演算子

val twoTimesNumber = number?.let { it * 2 } ?: 0 

elvis

val name: String = user?.name ?: "no name"

func

fun getLengthOfString(str: String): Int {
    return str.length()    
}

when

val word = when (value) {
  0 -> "zero"
  1 -> "one"
}

Singleton

object SingletonClass {
  var isFirstLaunch = false
}

小規模interfaceの省略

button.setOnClickListener(object :View.OnClickListener {
    override fun onClick(v: View?) { 

    }
})
↓
button.setOnClickListener { 
}

filter

var sum = 0
listOf(1,2,3).filter { it > 0 }.forEach {
  sum += it
}

リスト操作 http://kirimin.hatenablog.com/entry/2015/08/24/093646

変数展開

println("i is $i, user name is ${user.name}")

拡張

fun Int.square(): Int = this * this

プロパティ

class User {
    val id: Int
    var familyName: String = "yamada"
    var firstName: String = "taro"

    val fullName: String
        get() = "$familyName $firstName"
    var died: Boolean = false
        get() { return field }
        set(value) {
            field = value
            if (value) {
                println("${fullName}は死んでしまった")
            }
        }
    constructor(id: Int) {
        this.id = id
    }
}

データクラス(equals, hashCode, toString,copy が自動定義)

data class Vector3(val x: Double, val y: Double, val z: Double)

別名import

import android.graphics.Bitmap as ABitmap

enum

enum class Direction {
  NORTH, SOUTH, WEST, EAST
}
enum class Color(val rgb: Int) {
    RED(0xFF0000),
    GREEN(0x00FF00),
    BLUE(0x0000FF)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment