Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional way to evaluate boolean for a function that throws an exception

I'm trying to write the following function without using var and only val. Any ideas how to approach this ?

  def isValidBSONId(id: String): Boolean = {
    var valid: Boolean = false
    import reactivemongo.bson.utils.Converters._
    try {
      str2Hex(id)
      valid = true
    } catch  {
      case _ => valid = false
    }
    valid
  }
like image 987
Soumya Simanta Avatar asked Jan 21 '26 10:01

Soumya Simanta


1 Answers

Just Try{}.isSuccess

def isValidBSONId(id: String): Boolean = {
  import reactivemongo.bson.utils.Converters._
  Try(str2Hex(id)).isSuccess
}
like image 57
Eastsun Avatar answered Jan 24 '26 05:01

Eastsun