Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Unit type

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?

like image 912
Lydon Ch Avatar asked Jun 17 '10 14:06

Lydon Ch


People also ask

What is Unit data type in Scala?

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.

What is Unit return type in Scala?

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."

What is a Unit in Spark Scala?

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 .

What is a Scala type?

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.


2 Answers

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)

like image 115
mkneissl Avatar answered Sep 17 '22 01:09

mkneissl


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} ) { .... } 
like image 23
Vasil Remeniuk Avatar answered Sep 17 '22 01:09

Vasil Remeniuk