I’m relatively new to scala and made some really simple programs succesfully.
However, now that I’am trying some real world problem resolution, things are getting a little bit harder…
I want to read some files into ‘Configuration’ objects, using various ‘FileTypeReader’ subtypes that can ‘accept’ certain files (one for each FileTypeReader subtype) and return an Option[Configuration] if it can extract a configuration from it.
I’m trying to avoid the imperative style and wrote, for exemple, something like this (using scala-io, scaladoc for Path here http://jesseeichar.github.com/scala-io-doc/0.3.0/api/index.html#scalax.file.Path ) :
(...)
trait FileTypeReader {
import scalax.file.Path
def accept(aPath : Path) : Option[Configuration]
}
var readers : List[FileTypeReader] = ...// list of concrete readers
var configurations = for (
nextPath <- Path(someFolder).children();
reader <- readers
) yield reader.accept(nextPath);
(...)
Of course, that does not work, for-comprehensions return a collection of the first generator type (here, some IterablePathSet).
Since I tried many variant and feel like running in circle, I beg for you advices on that matter to solve my – trivial ? – problem with elegance ! 🙂
Many thanks in advance,
sni.
If I understand correctly, your problem is that you have a
Set[Path]and want to yield aList[Option[Configuration]]. As written,configurationswill be aSet[Option[Configuration]]. To change this to aList, use thetoListmethod i.e.or, change the type of the generator itself:
You probably actually want to get a
List[Configuration], which you can do elegantly sinceOptionis a monad: