1

我正在尝试将以下 Scala 2.9 隐式转换方法转换为 2.10 隐式类:

import java.sql.ResultSet

/**
 * Implicitly convert a ResultSet to a Stream[ResultSet]. The Stream can then be
 * traversed using the usual map, filter, etc.
 *
 * @param row the Result to convert
 * @return a Stream wrapped around the ResultSet
 */
implicit def stream(row: ResultSet): Stream[ResultSet] = {
  if (row.next) Stream.cons(row, stream(row))
  else {
    row.close()
    Stream.empty
  }
}

我的第一次尝试没有编译:

implicit class ResultSetStream(row: ResultSet) {
  def stream: Stream[ResultSet] = {
    if (row.next) Stream.cons(row, stream(row))
    else {
      row.close()
      Stream.empty
    }
  }
}

我收到语法错误,stream(row)因为stream不带参数。

这样做的正确方法是什么?

4

1 回答 1

5

尝试这个 :

scala> import java.sql.ResultSet
import java.sql.ResultSet

scala> implicit class ResultSetStream(row: ResultSet) {
     |     def stream: Stream[ResultSet] = {
     |       if (row.next) Stream.cons(row, row.stream)
     |       else {
     |         row.close()
     |         Stream.empty
     |       }
     |     }
     |   }
defined class ResultSetStream

你定义stream为函数,所以stream(row)不能工作。

您可以继承自AnyVal创建一个值类并优化您的代码:

implicit class ResultSetStream(val row: ResultSet) extends AnyVal {
    def stream: Stream[ResultSet] = {
      if (row.next) Stream.cons(row, row.stream)
      else {
        row.close()
        Stream.empty
      }
    }
  }
于 2013-02-05T17:55:40.907 回答