Reputation: 5621
I'm running a filter
command on an object in kotlin and trying to match results. I didn't realize until today that an empty string will match any string in a contains query as follows:
var brandname = ""
var brandtofind = "tide"
var result = brandtofind.contains(brandname) //results in true
This is problematic when you are trying to match entries where a string can be empty as follows:
var candidates = this.filter{ product ->
text.contains(product.name) ||
text.contains(product.brandname) //brandname often empty
I get massive numbers of false positives on products without a brand name. How do I alter the query to only match when there is a true match?
Upvotes: 0
Views: 33
Reputation: 6793
You can add a check for product.brandname.isNotBlank()
, which is an enhanced verions of isNotEmpty()
var candidates = this.filter{ product ->
text.contains(product.name) ||
(product.brandname.isNotBlank() && text.contains(product.brandname))}
Upvotes: 2