Ral*_*lph 1 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
}
}
Run Code Online (Sandbox Code Playgroud)
我的第一次尝试没有编译:
implicit class ResultSetStream(row: ResultSet) {
def stream: Stream[ResultSet] = {
if (row.next) Stream.cons(row, stream(row))
else {
row.close()
Stream.empty
}
}
}
Run Code Online (Sandbox Code Playgroud)
我收到语法错误,stream(row)因为stream没有参数.
这样做的正确方法是什么?
试试这个 :
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
Run Code Online (Sandbox Code Playgroud)
你定义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
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
613 次 |
| 最近记录: |