Correct idiom for a conditional return in scala

scala

Solution

You can sometimes use `Option` for cases where you want to return null (in Java).

I haven't compiled it, but it should work.

def snarf_image ( sUrl : String ) : Option[Array[Byte]] = {
   val bis = new BufferedInputStream(new URL(sUrl.replace(" ", "%20")).openStream())
   val bArray = Stream.continually(bis.read).takeWhile(-1 !=).map(_.toByte).toArray
   val img = ImageProcessing.ArrayToImage(bArray)
   if ( img.getHeight < 100 || img.getWidth < 100 ) {
     None
   } else {
     Some(bArray)
   }
}

Problem

I am trying to figure out the scala way to implment something I would do all the time in java. In java I would have snarf_image (below) return null if it meets the if condition, otherwise return the bArray. What is the scala way to do this? This code doesnt even compile and I cant figure out the right way to do it - Im sure my thinking is off. ``` def snarf_image ( sUrl : String ) : Array[Byte] = { val bis = new BufferedInputStream(new URL(sUrl.replace(" ", "%20")).openStream()) val bArray = Stream.continually(bis.read).takeWhile(-1 !=).map(_.toByte).toArray val img = ImageProcessing.ArrayToImage(bArray) if ( img.getHeight < 100 || img.getWidth < 100 ) { Empty } else { bArray } } ``` For the record I am using lift (hence using empty) but Im pretty sure this is more a scala question.

Original source

Related problems