Skip to content

Instantly share code, notes, and snippets.

@shiraji
Last active December 11, 2016 17:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shiraji/2caf8190d282ab3594a21b467980267e to your computer and use it in GitHub Desktop.
Save shiraji/2caf8190d282ab3594a21b467980267e to your computer and use it in GitHub Desktop.

Kotlinで気持ちいい!と思ったけど、落選した項目

JavaのPOJOクラス。HTTPレスポンス格納したりと結構活躍すると思います。

public class User {
    private String name;
    private int age;

    public User(name, age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public boolean equals(Object obj) {
        // 省略
    }

    public int hashCode() {
        // 省略
    }

    public String toString() {
        // 省略
    }

    // その他便利メソッド省略
}

コード書きすぎて手痛くなってきた・・・Kotlinでも書いてみます。

data class User(val name: String, val age: Int)

・・・気持ち良すぎる。

Javaをどうしても使いたいのであれば、auto-valueもありますので、腱鞘炎になる前にそちらを利用することを強くおすすめします。

あんまりやって良い例ではないのだけど・・・SparseArrayをループしたい場合、結構辛い。StackOverFlowからコードを借りると

for(int i = 0; i < sparseArray.size(); i++) {

これをKotlinで書くと

for (i in 0 until sparseArray.size()) {

他にもdownToとかstepとかいっぱいあるから公式確認して下さい。

Java7から利用出来る(Androidでは無理だけど)try-with-resources、Kotlinにもあって、useで書けます。

private fun copyAssetFileToCache(context: Context, assetFilePath: String, cacheFileName: String) {
        val cachedModelFile = File(context.cacheDir, cacheFileName)
        if (cachedModelFile.exists()) {
            cachedModelFile.delete()
        }
        FileOutputStream(cachedModelFile).use { outputStream ->
            context.resources.assets.open(assetFilePath).use { inputStream ->
                inputStream.copyTo(outputStream)
            }
        }
    }
    contentResolver.query(this.data, arrayOf(MediaStore.Images.Media.DATA), null, null, null).use {
        it.moveToFirst()
        return it.getString(it.getColumnIndexOrThrow(MediaStore.Images.Media.DATA))
    }

tryの外に出して、finallyでcloseしてと大変だったけど、かなりシンプルに書けます。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment