Scala Unit type

前端 未结 5 1377
情深已故
情深已故 2020-12-13 18:32

I use opencsv to parse csv files, and my code is

while( (line = reader.readNext()) != null ) { .... }

I got a compiler warning saying:

5条回答
  •  独厮守ぢ
    2020-12-13 19:02

    You can use a Stream to get what you want:

    Stream.continually(reader.readLine()).takeWhile( _ ne null) foreach { line =>
      //do Stuff
    }
    

    This has the added advantage of other cool stuff as well:

    Stream.continually(reader.readLine()).takeWhile( _ ne null) match {
      case head #:: tail => //perhaps you need to do stuff with the first element?
      case _             => //empty
    }
    

    EDIT - thanks to mkneissl for pointing out I should have included this warning:

    scala> Stream.continually(1).take(100000000).foreach(x=>()) 
    
    scala> val s = Stream.continually(1).take(100000000) 
    s: scala.collection.immutable.Stream[Int] = Stream(1, ?) 
    
    scala> s.foreach(x=>()) java.lang.OutOfMemoryError: Java heap space
    

提交回复
热议问题