Structural input for trace

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 that:

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 

He works.

I probably miss something so basic that I ignore it, but how can I do this?

+4
source share
1 answer

Int is sybtype AnyVal , so you need to explicitly declare it.

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

Source: https://habr.com/ru/post/1403390/


All Articles