What type of operator?

import scala.collection.immutable.ListMap

trait Foo {
  val begin: Int
}

object Test {
  def beginIndex[T <: Vector[Foo]](data: T): ListMap[Int, T] = {
    data.foldLeft(ListMap[Int, T]())({case (map, e) => map + ((e.begin, (map(e.begin) :+ e)))})
}

      

gives error

found   : scala.collection.immutable.Vector[Foo]
required: T

      

I'm guessing this <:

is the wrong type of operator, but I'm not sure which one would be the correct answer.

+3


source to share


1 answer


You are using the correct type operator, however, since you are using the scala api collection, you need to provide a builder for the type collections T

, otherwise scala will default to a builder Vector

which might return you Vector

not a T

. You can get this if you add a requirement for the implicit constructor T

:

def beginIndex[T <: Vector[Foo]](data: T)(implicit bf : CanBuildFrom[scala.collection.immutable.Vector[Foo], Foo, T]): ListMap[Int, T] = {
  data.foldLeft(ListMap[Int, T]())({case (map, e) => map + ((e.begin, (map(e.begin) :+ e)))})
}

      



If you are using a scala collection that inherits from Vector

then you might be in luck as it probably already has an imnplicit builder, although I'm not sure if you can get the types to develop, but Vector

should work. As a side note, I don't think you can work fine as map(e.begin)

it will always try to get a value from an empty map and throw an exception.

  println(Test.beginIndex(Vector(new Foo {
    override val begin: Int = 0
  })))

Exception in thread "main" java.util.NoSuchElementException: key not found: 0
    at scala.collection.MapLike$class.default(MapLike.scala:228)
    at scala.collection.AbstractMap.default(Map.scala:59)
    at scala.collection.MapLike$class.apply(MapLike.scala:141)
    at scala.collection.AbstractMap.apply(Map.scala:59)

      

+2


source







All Articles