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

scala – 可穿越的结构类型

发布时间:2020-12-16 18:19:55 所属栏目:安全 来源:网络整理
导读:我有这个方法: scala def foo(traversable: Traversable[{def toByte: Byte}]) = { | traversable.map(_.toByte) | }foo: (traversable: Traversable[AnyRef{def toByte: Byte}])Traversable[Byte] 但是当我这样称呼时: 阶 FOO(列表(1,2,3)) 我明白了: ja
我有这个方法:

scala> def foo(traversable: Traversable[{def toByte: Byte}]) = {
     | traversable.map(_.toByte)
     | }
foo: (traversable: Traversable[AnyRef{def toByte: Byte}])Traversable[Byte]

但是当我这样称呼时:

阶> FOO(列表(1,2,3))

我明白了:

java.lang.NoSuchMethodException
    at scala.runtime.BoxesRunTime.toByte(Unknown Source)
    at $anonfun$foo$1.apply(<console>:8)
    at $anonfun$foo$1.apply(<console>:8)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:194)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:194)
    at scala.collection.LinearSeqOptimized$class.foreach(LinearSeqOptimized.scala:59)
    at scala.collection.immutable.List.foreach(List.scala:45)
    at scala.collection.TraversableLike$class.map(TraversableLike.scala:194)
    at scala.collection.immutable.List.map(List.scala:45)
    at .foo(<console>:8)

但是,当我做这样的事情时:

scala> 1.toByte
res1: Byte = 1

有用.

我可能错过了一些基本的东西,我忽略了它,但我怎么能做到这一点呢?

解决方法

Int is sybtype of AnyVal,因此您需要明确声明它.

def foo(xs: Traversable[AnyVal { def toByte: Byte }]) = xs.map(_.toByte)

(编辑:李大同)

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

    推荐文章
      热点阅读