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 ""

coder25
  • 2,363
  • 12
  • 57
  • 104

1 Answers1

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))
Tanjin
  • 2,442
  • 1
  • 13
  • 20
  • thks it works but I have updated my question can u please check – coder25 Sep 18 '17 at 14:16
  • case where we need to change string to int-Can you please have a look at updated question – coder25 Sep 18 '17 at 14:17
  • Please check for scenerio 1 the `subject` field is also added which gives compile error with map – coder25 Sep 18 '17 at 14:33
  • That's because the original case class has an additional argument now. See updated answer – Tanjin Sep 18 '17 at 14:37
  • can u explain the _ used in scenerio 1 – coder25 Sep 18 '17 at 14:40
  • It's syntactic sugar, see a similar answer I did here: https://stackoverflow.com/questions/43302223/map-function-in-scala/43302468#43302468 – Tanjin Sep 18 '17 at 14:41
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/154703/discussion-between-coder25-and-tanjin). – coder25 Sep 18 '17 at 15:06
  • I have few more queries I have created a new question https://stackoverflow.com/questions/46282620/efficient-way-to-match-case-object-in-scala – coder25 Sep 18 '17 at 15:07