fun checkItem(arr: Array<String>, item: String): Boolean {
if (arr.indexOf(item) != -1) {
return true
} else {
return false
}
}
fun main() {
// create an array
val students = arrayOf<String>("Jacob", "Roy", "Yamini", "Neha")
// Check if Roy is in the array
val check_roy: Boolean = checkItem(students, "Roy")
println("Roy exists: " + check_roy)
// Check if Sohan is in the array
val check_sohan: Boolean = checkItem(students, "Sohan")
println("Sohan exists: " + check_sohan)
}
Output
Roy exists: true
Sohan exists: false
Explanation
If you are using Array List in Kotlin which is a mutable list and can be used to add or delete items easily using Kotlin built-in functions. You can also check if an item exists in an ArrayList or not using ArrayList.indexOf() function.
fun main() {
// initiaize array list
val students = ArrayList<String>()
students.add("Jacob")
students.add("John")
students.add("Somar")
if (students.indexOf("John") !== -1) {
println("Item exists in the array list")
} else {
println("item does not exist in the array list")
}
}
Output
Item exists in the array list
0 Comments