I have this method:
scala> def foo(traversable: Traversable[{def toByte: Byte}]) = {
| traversable.map(_.toByte)
| }
foo: (traversable: Traversable[AnyRef{def toByte: Byte}])Traversable[Byte]
But when I call it like so:
scala> foo(List(1,2,3))
I get:
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)
But when I do something like this:
scala> 1.toByte
res1: Byte = 1
It works.
I'm probably missing something so basic that I'm overlooking it, but how can I make this work?
Int
is sybtype of AnyVal
, so you need explicitly declare it.
def foo(xs: Traversable[AnyVal { def toByte: Byte }]) = xs.map(_.toByte)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With