2

I want to check for empty string in scala .If the string is empty return an option else return a None

Updated 1

 case class Student(name:String,subject:Symbol = Symbol("Default")))

  def getStudentName(name :Option[String]):Option[Student]={
     name.flatMap(_ => Option(Student(name.get)))
  }

Updated 2

Scenario 1:

 call 1- print(getStudentName(Option("abc")))//Some(Student(abc))
 Call 2- print(getStudentName(Option("")))//return Some(Student())

Scenario 2:

case class Emp(id:Int)

  def getEmp(id:Option[String]):Option[Emp]={
    id.flatMap(_ => Option(Emp(id.get.toInt)))
  }

  print(getEmp(Option("123")))
  print(getEmp(Option("")))//gives number format exception 

I want to return None when I pass ""

1 Answer 1

5

There is too much wrapping with Option going on, you can easily do:

Scenario 1:

name
  .filterNot(_.isEmpty)
  .map(Student(_))

Scenaro 2:

id
  .filterNot(_.isEmpty)
  .filter(_.matches("^[0-9]*$")) // ensure it's a number so .toInt is safe
  .map(id => Emp(id.toInt))
Sign up to request clarification or add additional context in comments.

8 Comments

thks it works but I have updated my question can u please check
case where we need to change string to int-Can you please have a look at updated question
Please check for scenerio 1 the subject field is also added which gives compile error with map
That's because the original case class has an additional argument now. See updated answer
can u explain the _ used in scenerio 1
|

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.