【问题标题】:Structural Typing for TraversableTraversable 的结构类型
【发布时间】:2012-03-26 04:05:21
【问题描述】:

我有这个方法:

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

但是当我这样称呼它时:

scala> foo(List(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

有效。

我可能遗漏了一些基本的东西,以至于我忽略了它,但是我怎样才能使它工作呢?

【问题讨论】:

    标签: scala structural-typing


    【解决方案1】:

    Intis sybtype ofAnyVal,所以需要明确声明。

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

    【讨论】:

      猜你喜欢
      • 2018-01-29
      • 1970-01-01
      • 2013-06-06
      • 2011-02-13
      • 2019-10-20
      • 2020-12-30
      • 1970-01-01
      • 2019-07-09
      • 1970-01-01
      相关资源
      最近更新 更多