Reputation: 32304
I ma trying to convert the following Scala 2.9 implicit conversion method to a 2.10 implicit class:
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
}
}
My first attempt does not compile:
implicit class ResultSetStream(row: ResultSet) {
def stream: Stream[ResultSet] = {
if (row.next) Stream.cons(row, stream(row))
else {
row.close()
Stream.empty
}
}
}
I get a syntax error on stream(row)
because stream
does not take a parameter.
What is the correct way to do this?
Upvotes: 1
Views: 627
Reputation: 1178
Try this :
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
You defined stream
as function, so stream(row)
can not work.
You can inherit from AnyVal
to create a Value Class and optimize your code:
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
}
}
}
Upvotes: 5