I use opencsv to parse csv files, and my code is
while( (line = reader.readNext()) != null ) { .... }
I got a compiler warning saying:
comparing values of types Unit and Null using `!=' will always yield true [warn] while( (aLine = reader.readNext()) != null ) {
How should I do the while loop?
The unit type is a child class of any type in the trait. This is used with the method signature in the scala as a return value. We should use this when we do not want our function to return any value.
In Scala we use the Unit return type to indicate "no return value." This is a "void" function. The void keyword is not used. Return An empty "return" statement can be used in a method that returns a Unit type. This means "no value."
Companion object Unit Unit is a subtype of scala. AnyVal. There is only one value of type Unit , () , and it is not represented by any object in the underlying runtime system. A method with return type Unit is analogous to a Java method which is declared void .
Scala is a statically typed programming language. This means the compiler determines the type of a variable at compile time. Type declaration is a Scala feature that enables us to declare our own types.
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)
In your case (line = reader.readNext()) is a functional literal that returns type Unit. You may rewrite the code as follows:
while( {line = reader.readNext(); line!= null} ) { .... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With