In what situations should abstract types be preferred over type parameters?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
To add to my previous answer on Abstract type vs. parameters, you have also the JESSE EICHAR’s recent blog post (2010, May 3rd) highlighting some key differences:
In
C2case,the parameter is "buried"(as an internal abstract type).(except, as retronym puts it, it is not actually buried, see below)
Whereas with generic type, the parameter is explicitly mentioned, helping other expressions to know what type they are supposed to used
So (C1: parameter):
It compiles, but you expose explicitly the ‘
A‘ type you want to use.And (C2: Abstract type):
It doesn’t compile because ‘
A‘ is never mentioned in p2 definition, sodoitdoesn’t know at compile type what it is supposed to return.When using abstract type and wanting to avoid any "type leaking" to the interface (i.e. wanting to expose what ‘
A‘ actually is), you could specify a very generic type as a return for p2:Or you could "fix" that type directly in the
doitfunction:def doit(a:A):Intinstead ofdef doit(a:A):A, which means:def p2(c:C2) = c.doit(c.get)will compile (even if p2 doesn’t mention any return type)Finally (retronym‘s comment) you can specify
Aeither explicitly by refining C2 abstract parameter:Or by adding a type parameter (and refining C2 abstract type with it!)
So abstract are recommended:
C2(but be wary of the definition of function usingC2)C2, use abstract type (with bounded type abstraction)C2types via traits, use abstract type (you won’t have ‘A‘ to deal with when mixingC2with your class: you mix onlyC2)For the rest, where simple type instantiation is need, use Parameters.
(if you know that no extension will be needed, but you still have to handle several types: that is what Parameter types are for)
retronym adds:
The main differences are
C2can only be invariant inA,(as illustrating here:
Dmytro Mitin adds in 2023 in the comments: