8
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Kotlinにて二つのバージョンの比較処理を実装しました。

Last updated at Posted at 2018-05-21

#概要
Androidにて強制バージョンアップの処理を実装する際に、
二つの異なるバージョンを比較する実装をKotlinにて実装しました。
Javaによる実装はあったのですがKotlinの実装例がなかったので投稿
こちらを参考にKotlin版を実装しました。

#実装内容

Version.kt

package jp.exam

import java.util.*

class Version: Comparable<Version> {
    private  var version: String
    private  var parts: List<String>

    constructor(version: String) {
        if(!version.matches(Regex("[0-9]+(\\.[0-9]+)+"))) {
            throw IllegalAccessException("Invalid version format")
        }
        this.version = version
        this.parts   = version.split(Regex("\\."))
    }

    override fun compareTo(other: Version): Int {
        val length = Math.max(this.parts.size, other.parts.size)
        for (i in 0..(length - 1)) {
            val thisPart = if(i < this.parts.size) this.parts[i].toInt() else 0
            val otherPart = if(i < other.parts.size) other.parts[i].toInt() else 0

            if (thisPart < otherPart) {
                return -1
            }
            if (thisPart > otherPart) {
                return 1
            }
        }
        return 0
    }

    override fun equals(other: Any?): Boolean {
        if (this == other) return  true
        if (other == null) return  false
        if (this::class.java.name != other::class.java.name) {
            return false
        }
        return this.compareTo(other as Version) == 0
    }
}

#使い方

val currentAppVersion = Version("1.0.0")
val latestVersion     = Version("1.1.0")
Log.d("Result", currentAppVersion.compareTo(latestVersion)) // -1

val currentAppVersion = Version("1.0.0")
val latestVersion     = Version("1.0.0")
Log.d("Result", currentAppVersion.compareTo(latestVersion)) // 0

val currentAppVersion = Version("1.0.1")
val latestVersion     = Version("1.0.0")
Log.d("Result", currentAppVersion.compareTo(latestVersion)) // 1

Androidの場合VersionCodeで比較すればもっと楽に分岐できるのですが、
様々なバージョンへの応用とiOSとの実装を合わせるという観点から実装してみました。

#参照
2つのバージョンで処理を分岐させたいときの、バージョン文字列の比較(Java実装)

8
3
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
8
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?