0

I'm having this class

class Product(val price: BigDecimal, val tag: String)

Then I add items to this class

 var products = ArrayList<Product>()

 for (i in 1..5) {
     products.add(Product((0.25 * i).toBigDecimal(), i.toString()))
 }

Now I can view the items like this

products.forEach {
    Log.d("xxx", "price: ${it.price} tag: ${it.tag}")
}

Results:

D/xxx: price: 0.25 tag: 1
D/xxx: price: 0.5 tag: 2
D/xxx: price: 0.75 tag: 3
D/xxx: price: 1.0 tag: 4
D/xxx: price: 1.25 tag: 5

What I'm trying to do is, find "price" with "tag" = "3" in products. I'm using this code but it gives me null.

var f = products.find { it.tag.equals('3') }

Any ideas?

2 Answers 2

1

Answer is already inside your question.

You are trying to save tag as "tag" = "3" but you are trying to retrieve with it.tag.equals('3').

Simply you have to change your code with it.tag.equals("3")

Replace this line

var f = products.find { it.tag.equals('3') }

with this

 var f = products.find { it.tag.equals("3") }
Sign up to request clarification or add additional context in comments.

Comments

1

The problem is that "3" and '3' are different. '3' is the character of the number 3 and "3" is a string that contains the character of 3. By using equals function, in fact, you are getting false always in the predicate due to inequality of String and Char types. So, if you change the code like the following, the problem will be solved:

var f = products.find { it.tag == "3" }

Note that == in kotlin is the operator function of equals which makes it simpler to read and write.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.