Alternative way to check if a string contains multiple strings in Kotlin?

Viewed 40

I currently have the following code

fun main() {
    // Build.Fingerprint sample strings
    val debug_fingerprint: String? = "Company/device/device:11/3526.4353/0064504902000:userdebug/com-d,dev-keys"
    val dev_fingerprint: String? = "Company/device/device:11/526.4353/0064504902000:user/com-d,dev-keys"
    val user_fingerprint: String? = "Company/device/device:11/526.4353/0064504902000:user/com-p,release-keys"
    

    //Testing
    val osVarient: String = user_fingerprint?.let {
            when {
                check(listOf("userdebug", "dev-keys"), it) -> "Userdebug"
                check(listOf("user", "dev-keys"), it) -> "Userdevsigned"
                check(listOf("user", "release-keys"), it) -> "User"
                else -> "Unknown variant"
            }
        } ?: run {
            "Unknown variant null"
        }  
    print(osVarient)
}
fun check(args: List<String>,fingerprint: String): Boolean {
    for(arg in args) {
        if(!fingerprint.contains(arg)){
            return false
        }
    }
    return true
}

The above code works but I'm wondering if there is more elegant way of writing the code.

Are there any alternatives in Kotlin to compare multiple substrings to a string?

1 Answers

You may use a dictionary for OS variants. Iterable<T>.all is a builtin kotlin stdlib function to check a predicate on all elements.

fun main() {
  val userFingerprint: String? = "Company/device/device:11/526.4353/0064504902000:user/com-p,release-keys"

  val variantMap = mapOf(
      "Userdebug" to listOf("userdebug", "dev-keys"),
      "Userdevsigned" to listOf("user", "dev-keys"),
      "User" to listOf("user", "release-keys")
  )

  val osVariant = userFingerprint?.let { fingerprint ->
    variantMap.entries
        .firstOrNull { check(it.value, fingerprint) }
        ?.key
  } ?: "Unknown variant null"

  println(osVariant)
}

fun check(fingerprintTypes: List<String>, fingerprint: String): Boolean {
  return fingerprintTypes.all { it in fingerprint } 
  // return fingerprintTypes.all { fingerprint.contains(it) }
}
Related