Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structural Typing for Traversable

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?

like image 856
Mike Lewis Avatar asked Dec 28 '22 03:12

Mike Lewis


1 Answers

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

def foo(xs: Traversable[AnyVal { def toByte: Byte }]) = xs.map(_.toByte) 
like image 121
4e6 Avatar answered Jan 20 '23 11:01

4e6