title: Scala: How to return a Some or Option
body: <p>I have the following piece of code that I am trying to enhance:
  I am using the <code>java.nio.file</code> package to represent a directory or a file as a <code>Path</code>.
  So here goes:</p>
  
  <pre><code>import java.nio.file.{Paths,DirectoryStream,Files,
                        Path,DirectoryIteratorException}
  
  val path: Path = Paths.get(directoryPath) 
  var directoryStream: Option[DirectoryStream[Path]] = None
  
  // so far so good
  
  try {
      directoryStream = Some(Files.newDirectoryStream(pathO))
  
      // this is where i get into trouble
      def getMeDirStream: DirectoryStream[Path] =
          if (!directoryStream.isEmpty &amp;&amp; directoryStream.isDefined)
              getMeDirStream.get
          else
              None
  
      // invoke the iterator() method of dstream here
  }
  </code></pre>
  
  <p>The above piece of code will not compile because I do not know what to return in the else, and right now, for the life of me, I can only come up with <code>None</code>, which the compiler simply does not like and I would like to learn what should be its replacement. 
  I want this example to be a learning lesson of <code>Option</code> and <code>Some</code> for me.</p>
  
  <hr>
  
  <p>Okay, this is where I choke. I would like to check if the <code>directoryStream</code> is not empty and is defined, and then if this is the case, I would like to invoke <code>getMeDirStream.get</code> to invoke the <code>iterator()</code> method on it. 
  The API for <code>Option</code> tells me that invoking the <code>get()</code> method could result in a <code>java.util.NoSuchElementException</code> if the option is empty. </p>
  
  <p>If the directoryStream is empty I want to return something and not None, because IntelliJ is telling me that "Expression of type <code>None.type</code> doesn't conform to expected type <code>DirectoryStream[Path]</code>".</p>
  
  <p>Now, I am being all naive about this. </p>
  
  <p>I would like to know the following:</p>
  
  <ol>
  <li><p>What should I return in the <code>else</code> other than <code>None</code>?</p></li>
  <li><p>Should I wrap the <code>getMeDirStream.get</code> in a try-catch with a <code>java.util.NoSuchElementException</code>, even though I am checking if the <code>directoryStream</code> is empty or not.?</p></li>
  <li><p>What is the purpose of a try-catch in the <code>getMeDirStream.get</code>, if there is indeed such a need? </p></li>
  <li><p>How can I clean up the above piece of code to incorporate correct checks for being <code>isDefined</code> and for catching appropriate exceptions?</p></li>
  </ol>
  
  <p>Once I know what to return in the else (and after putting in the appropriate try-catch block if necessary), I would like to invoke the <code>iterator()</code> method on <code>getMeDirStream</code> to do some downstream operations.</p>