2

I'm having trouble defining a method using generic parameters in Scala.

Let's say I want a something like this:

class CollectionConverter {
   def convertListToSet(list: java.util.List[SomeType]): java.util.Set[SomeType] = {
     val s = new java.util.HashSet[SomeType]
     s.addAll(list)
     s
   }
}

I can't seem to find a way to make Scala understand that I don't know what SomeType is, just that whatever it is, the returned generic set will have the same generic type as the supplied list. It complains that I haven't defined SomeType. But that's the thing -- I don't know or care what SomeType is, it could be called YeahYeahYeah for all I care.

I don't want to use List[Any], and List[_] creates other problems, so... what's the right way to do this?

Any help would be greatly appreciated!

1 Answer 1

4

That's what type parameters for methods are for.

def convertListToSet[SomeType](list: java.util.List[SomeType]): java.util.Set[SomeType] = {
   val s = new java.util.HashSet[SomeType]
   s.addAll(list)
   s
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ahhhhhh so close! So close. Thanks VERY much, that's exactly what I needed.

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.