Scala Unit type

前端 未结 5 1379
情深已故
情深已故 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 18:57

    An assignment expression has type Unit in Scala. That is the reason for your compiler warning.

    There is a nice idiom in Scala that avoids the while loop:

    val iterator = Iterator.continually(reader.readNext()).takeWhile(_ != null)
    

    This gives you an iterator over whatever reader.readNext returns.

    The continually method returns an "infinite" iterator and takeWhile takes the prefix of that, up to but not including the first null.

    (Scala 2.8)

提交回复
热议问题