0

How can I use nested type in Scala generic function ? I'd like to implement something like this

implicit def basicDBList2List[List[A]](value : BasicDBList) = value.toList.asInstanceOf[List[A]]

Compiler gives following error:

scala: not found: type A
  implicit def basicDBList2List[List[A]](value : BasicDBList) = value.toList.asInstanceOf[List[A]]
                                                                                               ^

2 Answers 2

2

When you write:

implicit def basicDBList2List[List[A]](value: BasicDBList) = ...

... that doesn't mean what you think it means. You're declaring a new type parameter called List, not referring to the existing List trait in the library! You're also declaring that your newly-defined List type requires some type parameter, which you've called A, but you can't actually reference it.

What you probably meant was:

implicit def basicDBList2List[A](value: BasicDBList): List[A] = ...

... which says that, for any type A, you can convert a BasicDBList to a List[A].

This is sketchy code, though, for two reasons:

  1. What type does your BasicDBList class actually contain? Probably not any possible A. You'll very likely get ClassCastException at runtime.
  2. Why do you want an implicit conversion from BasicDBList to List[A]? That's almost always a bad idea.
Sign up to request clarification or add additional context in comments.

2 Comments

I have to wrap shitty mongo java driver so I don't have to pollute client code with casting. So basically when I fetch particular field from Mongo DB I know what type it is.
Shitty casbah is the reason I started playing with implicits :)
0

I think it is better have it like:

implicit def basicDBList2List[A](value : BasicDBList) = value.toList.asInstanceOf[List[A]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.