TL ; DR:
x in list is true when the list holds x, and false when it doesn't. Use x !in list for the opposite.
val colors = mutableListOf("red", "green", "blue")
println("red" in colors) // true
println("pink" in colors) // false
if ("pink" !in colors) {
println("No pink yet")
}
Full lesson:
Often you need to know if a list holds some value. Is this name on the guest list? Is this item in the cart?
x in list answers that. It compares each item with x, from the first one on. It gives true as soon as one matches, or false if none does.
Use !in for the opposite. So x !in list is true when x is missing.
The answer is a Boolean, so it fits right into an if:
val cart = mutableListOf("milk", "bread")
if ("milk" in cart) {
println("Milk is in the cart")
}
The in operator calls the list's contains method for you. So colors.contains("red") gives the same answer.
Text must match exactly. So "Red" in colors is false, because the list has "red".
Your task
bag holds what is packed for a hike.
If "water" is in bag, print Water is packed. If "tent" is not in bag, print Pack a tent.
Expected output:
Water is packed
Pack a tentFree plan: 30 tutor messages. PRO is unlimited.
