0

I have a task need to find a particular string in an array: 1. if found, return its value; 2. if not found, return -1.

I wrote an "idea" code, but I don't know how to finish it correctly.

case class person(name:String, value: Int)
personList[Array[person]]

val result = personList match { 
case x if x.name == "john" => x.value
case _ => -1 }

the complier reports errors at "case x if x.name"

2
  • If found return value, i.e. String. If not found return -1, i.e. Int. That doesn't sound right. String and Int are different types. Commented Apr 19, 2017 at 1:21
  • Sorry, changed it to Int Commented Apr 19, 2017 at 1:24

2 Answers 2

1

Would this work for you?

persons.find(_.name == "john").fold(-1)(_.value)

Note: I've left the creation and/or population of the persons array up to you.

Sign up to request clarification or add additional context in comments.

Comments

0
val result = personList.find(_.name=="john") match { 
case some(x) => x.value
case None => -1 }

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.