加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

使用Scala 2.10隐式类转换为“内置”标准库类

发布时间:2020-12-16 10:02:46 所属栏目:安全 来源:网络整理
导读:我试图使用新的 Scala 2.10隐式类机制将java.sql.ResultSet转换为scala.collection.immutable.Stream.在Scala 2.9中,我使用以下代码,它有效: /** * Implicitly convert a ResultSet to a Stream[ResultSet]. The Stream can then be * traversed using the
我试图使用新的 Scala 2.10隐式类机制将java.sql.ResultSet转换为scala.collection.immutable.Stream.在Scala 2.9中,我使用以下代码,它有效:

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

我可以这样使用它:

val resultSet = statement.executeQuery("SELECT * FROM foo")
resultSet.map {
  row => /* ... */
}

我想出的隐式类看起来像这样:

/**
 * Implicitly convert a ResultSet to a Stream[ResultSet]. The Stream can then be
 * traversed using the usual map,etc.
 */
implicit class ResultSetStream(val row: ResultSet)
  extends AnyVal {
  def toStream: Stream[ResultSet] = {
    if (row.next) Stream.cons(row,row.toStream)
    else {
      row.close()
      Stream.empty
    }
  }
}

但是,现在我必须在ResultSet上调用toStream,这种方式会破坏“隐含”部分:

val resultSet = statement.executeQuery("SELECT * FROM foo")
resultSet.toStream.map {
  row => /* ... */
}

我究竟做错了什么?

我是否仍应使用隐式def并导入scala.language.implicitConversions来避免“功能”警告?

UPDATE

以下是将ResultSet转换为scala.collection.Iterator(仅Scala 2.10)的替代解决方案:

/*
 * Treat a java.sql.ResultSet as an Iterator,allowing operations like filter,* map,etc.
 *
 * Sample usage:
 * val resultSet = statement.executeQuery("...")
 * resultSet.map {
 *   resultSet =>
 *   // ...
 * }
 */
implicit class ResultSetIterator(resultSet: ResultSet)
extends Iterator[ResultSet] {
  def hasNext: Boolean = resultSet.next()
  def next() = resultSet
}

解决方法

我没有看到使用隐式类的原因.坚持你的第一个版本.隐式类主要用于(如“简明”)将方法添加到现有类型(所谓的“丰富我的库”模式).
它只是包装类的语法糖和对此类的隐式转换.

但在这里,您只是(隐式地)从一个预先存在的类型转换为另一个预先存在的类型.根本不需要定义新类(更不用说隐式类).

在您的情况下,您可以通过使ResultSetStream扩展Stream并实现作为toStream的代理来使其使用隐式类.但那真的很麻烦.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读