item in array or array.contains(item). What made ...
# getting-started
b
item in array or array.contains(item). What made me laugh was https://stackoverflow.com/questions/42234775/kotlin-idiomatic-way-to-check-array-contains-value. The posters seemed to want to find the cleverest, most complex way of doing it rather than answering the question. 'item in array' seems the most elegant but is it idiomatic?
j
I think the accepted answer is pretty reasonable, I don't quite get why this doesn't answer your question. Basically you can use both depending on how readable you find them. I usually use
in
inside
if
conditions because I like how it reads. Sometimes
contains
might feel more natural if it's at the end of a chain of calls. In other cases, I don't mind, I guess it's opinion based anyway
By the way, you might want to ask those in #codingconventions
👃 1
e
item in array
is idiomatic
the use of
Array
in general is not
b
Thanks
@Joffrey another great channel.
Think I may have found a case for ArrayList
fun dropLoot(name: String): Boolean {
println("$name will be dropped")
return inventory.removeIf { it.name = name }
}
cant work out how to do this for mutanleListOf
e
the Kotlin method is
Copy code
inventory.removeAll { it.name == name }
removeIf
comes from Java
a
removeIf
seems to work on
mutableListOf
🤔
but it won’t work like written in
dropLoot
since it mutates the list, and returns a boolean
b
Sorry don't quite follow
a
I suppose you want
==
there and not
=
âž• 1
e
you must have set something up wrong;
removeIf
is one of the new default methods in Java 8: https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#removeIf-java.util.function.Predicate- and as such it is callable on a
MutableList
as long as you're on JVM
==
vs
=
would break regardless of `ArrayList`/`MutableList`…
b
OK, but removeIf still red. Think I may need to use removeAll, just looking into syntax
a
seems to work on my machine at least 🙂
Copy code
data class Thing(
        val name: String
    )

    val inventory = mutableListOf<Thing>(Thing("foo"), Thing("bar"), Thing("baz"))
    println(inventory) // [Thing(name=foo), Thing(name=bar), Thing(name=baz)]
    inventory.removeIf { it.name == "foo" }
    println(inventory) // [Thing(name=bar), Thing(name=baz)]
b
Interesting
But I can do it with
Copy code
fun dropLoot(name: String): Boolean {
    println("$name will be dropped")
    return inventory.retainAll { it.name != name }
}
e
that may mean you don't have jvmTarget="1.8"
anyhow, largely irrelevant; just use Kotlin's
removeAll
or
retainAll
.
b
Thanks, where do I find my jvmTarget? I'm using the latest Android Studio.
j
@Ben Edwards it should be in one of your
build.gradle(.kts)
files - or nowhere at all, but I think the default is now 1.8 so if you have no such setting you should also have no such problem 😄
👃 1