Scala difference between type T and [T]

Possible duplicate:
Scala: abstract types and general characteristics

As I understand it, the following two class definitions are the same. So what is the difference besides the syntax?

abstract class Container[T] {} class IntContainer extends Container[Int] {} abstract class Container2 { type T } class IntContainer2 extends Container2 { type T = Int } 

When I look at the decompiled bytecode, I notice that the first set still has generics (although the IntContainer is defined as having the type Object: public class IntContainer extends Container<Object> ). The second set does not have such information. I thought that all generic types were erased anyway ...

PS Using Scala 2.10-M5

+4
source share
1 answer

There is a clear difference between abstract types and generics, which we should always remember:

  • If a class is a generic type, multiple instances of the same class can have a different generic type
  • If a particular class is an abstract type, for a given Scala class, all instances of this (this) class will have the same abstract type.

It should now be clear to you that they can be used differently:

  • Generics are primarily intended for a class that needs to act like containers or business classes that need to perform some operations for a given purpose. In this sense, a generic parameter allows you to check type safety at compile time.
  • Abstract types are primarily intended to define behavior or property at a higher level and to refine it when subclassed. Generics have little to do with inheritance.

If you look at a different perspective, while the generic GenericClass [T] and T method is the parameter for the method, it is much less likely to develop a method that receives ClassWithAbstractTypeT and classWithAbstractType. T. Actually, coding of such a method in Scala 2.9 is prohibited if path-dependent chords are active (if I am not mistaken, by default they are active in 2.10)

+1
source

All Articles