LoginSignup
4
1

More than 5 years have passed since last update.

Kotlinいいとこまとめ②

Posted at

いいとこまとめ

こちらの続編
あんまいい例が思い浮かばないのはご勘弁を。。

プロパティ

前回もプロパティ触れたんですが。
バッキングフィールドを自動で生成してくれる。
いちいちバッキングプロパティ用意しなくていい。素敵。

BackingProperty
public var text: String = "Kotlin"
    get() = "Hello " + _foo
    set(value) {
        _foo = value
    }
private var _text = ""
BackingFiled
public var text: String = "Kotlin"
    get() = "Hello " + field

if文ではなくif式である

これなら便利さが伝わる...はず...

val str1 = "Hello"
val str2 = "World"
val string: String = if (str1 === "Hello") {
    if (str2 == "World") str1 + " " + str2 else "Kotlin"
} else {
    "Bye"
}

シングルトン

Android Javaのシングルトンはいまいちだった。
参考
ちょー簡単。

object SingletonObject {
    val hoge : Int = 1
}

Extension

きたーー
もう語るまでもないですね
公式から拝借

fun MutableList<Int>.swap(index1: Int, index2: Int) {
    val tmp = this[index1] // 'this' corresponds to the list
    this[index1] = this[index2]
    this[index2] = tmp
}

Nullable

きたーー
こちらも語るまでもないですね
同じく公式から拝借

var a: String = "abc"
a = null // compilation error

コンストラクタ

らくちん

Java
class Foo {
    private final String name;

    Foo(String name) {
        this.name = name;
    }
}
Kotlinにそのまま直すとこう
class Foo(name: String) {
  private val name = name
}
もうちょい省略できる
class Foo(private val name: String) {
}

アクセス修飾子

デフォルトでpublic final
継承されるの想定されないのにfinalじゃないのが嫌で嫌で毎回毎回finalつけてたぼく歓喜。

あとはtoとかかなー。これは次回。

株式会社Arrvis

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1