Type erasure

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Type erasure

Tim Pigden
Hi
I have a very simple class which effectively amounts to:
class ColouredThings (
        val colour: Colour
      val name: String
)

And a class with two methods defined

def add(list: List[ColouredThings])) ....
def add(list: List[(Colour, String)]) .....

the second method was added simply to make my junit tests more readable
and quicker to write
I'm getting a compiler message
Error: double definition:
..
Has same type after erasure

Is this to be expected?

Tim
Reply | Threaded
Open this post in threaded view
|

Re: Type erasure

Jan Lohre
Short answer: Yes.

Longer Answer: As in Java, type parameters are only available at compile time. Therefore both List[A] and List[B] have the same type List, hence your methods have both the same parameter types. Thats called type erasure.

You could instead introduce an implicit conversion like for example
implicit def listOfTupleToListOfColouredThing(tuples : List[(Colour,String)]) = tuples.map(tuple => new ColouredThing(tuple._1,tuple._2))

When this is in scope at the call site you can do
add((Colour.RED, "red")::(Colour.BLUE, "blue")::Nil)

with only the following method defined
def add(list: List[ColouredThings])) ....

Or you could do
implicit def tupleToColouredThing(tuple : (Colour,String)) = ...

add(List[ColouredThing]((Colour.RED, "red"), (Colour.BLUE, "blue")))

I hope this helps.

Kind regards,
Jan

2009/5/17 Tim Pigden <[hidden email]>
Hi
I have a very simple class which effectively amounts to:
class ColouredThings (
       val colour: Colour
     val name: String
)

And a class with two methods defined

def add(list: List[ColouredThings])) ....
def add(list: List[(Colour, String)]) .....

the second method was added simply to make my junit tests more readable
and quicker to write
I'm getting a compiler message
Error: double definition:
..
Has same type after erasure

Is this to be expected?

Tim