代码之家  ›  专栏  ›  技术社区  ›  Lydon Ch

斯卡拉单位类型

  •  31
  • Lydon Ch  · 技术社区  · 15 年前

    我使用opencv解析csv文件,我的代码是

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

    我收到一个编译器警告说:

     comparing values of types Unit and Null using `!=' will always yield true
     [warn]     while( (aLine = reader.readNext()) != null ) {
    

    我该怎么做while循环?

    5 回复  |  直到 15 年前
        1
  •  19
  •   Vasil Remeniuk    15 年前

    在您的情况下(line=reader.readnext())是返回类型单位的函数文本。您可以按如下方式重写代码:

    while( {line = reader.readNext();  line!= null} ) { .... }
    
        2
  •  70
  •   mkneissl    15 年前

    赋值表达式具有类型 Unit 在斯卡拉。这就是编译器警告的原因。

    scala中有一个很好的习惯用法,可以避免while循环:

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

    这会给你一个迭代器 reader.readNext 返回。

    这个 continually 方法返回“无限”迭代器和 takeWhile 取其前缀,最多但不包括第一个空值。

    (Scala 2.8)

        3
  •  17
  •   oxbow_lakes    15 年前

    你可以使用 Stream 想要得到你想要的:

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

    这也增加了其他酷东西的优势:

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

    编辑 - 感谢mkneisl指出,我应该包括这个警告 :

    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
    
        4
  •  10
  •   Jesper    15 年前

    你正在编写Scala代码,你会用Java编写它。试着用一种更像scala的方式来做。要逐行读取文本文件并对每行执行某些操作,请尝试以下操作:

    import java.io.File
    import scala.io.Source
    
    Source.fromFile(new File("myfile.txt")).getLines.foreach { line =>
        // Do something with the line, for example print it
        println(line)
    }
    
        5
  •  3
  •   Don Mackenzie    15 年前

    Scala中的赋值不返回一个值,单位类似于C或C++中的空格。

    尝试

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

    这是因为返回了块中最后一个表达式的值,在这种情况下,它是 虽然