Why scala's pattern maching does not work in for loops for type matching?

后端 未结 3 795
盖世英雄少女心
盖世英雄少女心 2020-12-10 15:25

I\'m coding against an API that gives me access to remote file system. The API returns a list of files and directories as list of node objects (parent to file and directory)

相关标签:
3条回答
  • 2020-12-10 16:12

    What you want to do is essentially: iterate over all elements of workarea.getChildren() that are of type CSDir (in other words: matching some criteria). Ordinary loop/for comprehension iterates over all elements. You cannot say: iterate over all elements having this type and skip others. You must be more explicit.

    What do you think about:

    workarea.getChildren() collect {case dir: CSDir => dir} foreach println
    

    It does exactly what you want: collect all elements of workarea.getChildren() and for each of them call println.

    0 讨论(0)
  • 2020-12-10 16:12

    How about this:

    val listOfBaseObjects: List[Any] = List[Any]("a string", 1:Integer);
    
    for (x <- listOfBaseObjects if x.isInstanceOf[String]) {
      println(x)
    }
    
    0 讨论(0)
  • 2020-12-10 16:14

    This is the long-standing issue 900 and has been discussed many times before. The common workaround is to use something like:

    for (y@(_y:String) <- listOfBaseObjects) {
        println(y)
    }
    

    A nicer version is provided by Jason Zaugg in the comments to the above-mentioned ticket:

    object Typed { def unapply[A](a: A) = Some(a) }
    
    for (Typed(y : String) <- listOfBaseObjects) {
        println(y)
    }
    
    0 讨论(0)
提交回复
热议问题