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

scala – 为什么要寻找String?

发布时间:2020-12-16 09:09:18 所属栏目:安全 来源:网络整理
导读:给出以下代码: abstract class Field { type T val data: List[T] def sum: T = data(0) + data(1)} 我在最后一行得到一个错误 – def sum:T = data(0)data(1): types2.scala:6: error: type mismatch; found : Field.this.T required: String def sum: T
给出以下代码:

abstract class Field {
  type T
  val data: List[T]
  def sum: T = data(0) + data(1)
}

我在最后一行得到一个错误 – def sum:T = data(0)data(1):

types2.scala:6: error: type mismatch;

found : Field.this.T

required: String

def sum: T = data(0) + data(1)

06001

也就是说,它期望data(1)是String.
我不明白为什么……(scala 2.8.1)

非常感谢您的解释!

解决方法

由于T不支持加法运算,因此编译器假定为字符串连接操作.我在REPL尝试的以下行表明:

scala> implicitly[Any => {def +(s: String): String}]
res16: (Any) => AnyRef{def +(s: String): String} = <function1>

您可以做的是要求T定义了Semigroup代数. (如果类型支持关联追加操作,则类型为半群.)

scala> import scalaz._
import scalaz._

scala> import Scalaz._
import Scalaz._

scala> abstract class Field[A : Semigroup] {
     |   val data: IndexedSeq[A]
     |   def sum: A = data(0) |+| data(1)
     | }
defined class Field

scala> val f = new Field[Int] {
     |   val data = IndexedSeq(2,3,4)
     | }
f: Field[Int] = $anon$1@d1fd51

scala> f.sum
res12: Int = 5

我用类型参数替换了抽象类型,因为我不知道如何在抽象类型上放置上下文绑定.我还将List [A]中的数据类型更改为IndexedSeq [A],因为名称表示索引序列比列表更适合索引访问(这是您在sum方法中执行的操作).最后,| |是半群追加操作.对于数字类型,它将执行添加.对于序列,连接等.

(编辑:李大同)

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

    推荐文章
      热点阅读