将Scala隐式转换方法转换为2.10隐式类

时间:2013-02-05 17:39:38

标签: scala implicit-conversion

我试图将以下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没有参数。

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

1 个答案:

答案 0 :(得分: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以创建Value Class并优化您的代码:

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
      }
    }
  }