scala - Elegant Way to Check toInt or toBoolean -


I have a group of fields that I am parsing in XML and they are int or type on the basis of boolean field The problem is that in some cases of the XML file this tag may not exist, it naturally throws a runtime error when I have a blank for boolean or int Try to convert code> string . I'm new to Scala, is there a way to use the option class to make it better?

This is how the code looks without the handle. Parental node is always present but can not have hair nodes or fields. itemprop = "text"

  (parentNode / childNote / area) .text.toBoolean    

You can use scala.util.Try for it. If code inside try -block is successful, it will give a success (result) . Otherwise a failure (exception) has been refunded. Try

  (parentNode / childNote / field) .text.toBoolean)   

From here you have several options to deal with it. I guess That, in the case where the area does not exist, you have no default value

1 failure is not important, then you can use directly in getOrElse and in a failure case default value will be used. Try

  (parentNode / childNote / area) .text.toBoolean) .getOrElse (DefaultValue)   

2 Pattern-Mailing

It should be used only when you have many ways of calling and / or exception handling.

  (parentNode / childNote / field) .text.toBoolean) match {case success (bull) = & gt; {// calculations} case failure (former) = & gt; {// do something with exception}}    

Comments

Popular posts from this blog

ios - Adding an SKSpriteNode to SKScene from a child SKSpriteNode -

Matlab transpose a table vector -

c# - Textbox not clickable but editable -