Question

I am having some difficulty making my function generic, and need some help. I have an array that takes Option's of T where T is a Fractional. In F#, there is a function "choose" which strips None's from a collection of Options. In scala, I am trying to use "flatten", but it does not work with a generic type.

my code is

var arr = Array.fill(capacity)(None :Option[T])

... and later I try to get values of the Some's :

var flat = arr.flatten

error is:

error: could not find implicit value for parameter m: scala.reflect.ClassManifest[U] val flat = arr.flatten

i am a complete scala noob, and maybe should not play with generics :) how do i make this work?

Thanks!

Was it helpful?

Solution

The problem is that you are trying to create a new generic array, and your method doesn't know how because arrays require type information. You should then add a ClassManifest context bound so that the array knows how to create itself:

def flat[T: ClassManifest](bumpy: Array[Option[T]]): Array[T] = bumpy.flatten
val fish = Array(Some("salmon"), None, Some("haddock"))
flat(fish)  // Prints Array(salmon, haddock)

Note that if you try to pass the array in directly to the method, it will get confused trying to figure out what type it is; you need the assignment for a val to let it know that the array itself contains all the information about its type, and then flat should take its type from the array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top