2

I'm not very familiar with scala so I hope that my question makes sense:

I have a complex parametrised class, but lets resume it to:

class Foo[T] {
    def foo(x: T) = {/*do something*/}
}

Now In another part of the program, I would like to build something like:

val mylist = List[Foo[_]](new Foo[Int], new Foo[String], ...)

I'd like to be able to do something like:

mylist(0).foo(2)

but get

Type mismatch: expected _$1, actual: Int

I think it can be resolved with TypeTags but I couldn't adapt any of the material I saw on this subject. Here I'd like to tell the Foo that it' supposed to be parametrised by an Int.


Moreover, In the actual use case, I'll get a variable :

val x : Any 

I know that it matches a mylist(i), but I don't know either the type of the Foo[_] located at mylist(i) or the type of x. Yet I'd like to do something like :

mylist(i).foo(x)

or in my mind (but this barely make sense in scala) :

mylist(i).asInstanceOf(Foo[x.getClass]).foo(x.asInstanceOf(x.getClass))

How can I do that ?

I know there are plenty of post on subjects close to this one but I can't figure this out.

Christian Neverdal
  • 4,815
  • 5
  • 32
  • 87
AntoinePrv
  • 21
  • 3
  • 1
    You're looking for an [`HList`](https://github.com/milessabin/shapeless), but existential types and reflection can only get you so far. An existential type tells the compiler _I don't care what this type is_. – Michael Zajac May 19 '16 at 15:52
  • 2
    As soon as you've got a `List[_]` you're out of luck—you can use "type casing" in a pattern match (which is inherently broken on generic types and arguably bad anyway) or `asInstanceOf` (which is possibly even worse), but essentially you've lost type safety and the compiler can't help you if the thing you're telling it is a lie. – Travis Brown May 19 '16 at 15:55

0 Answers0