Reputation: 4546
I'm having trouble finding what this is called and what the difference is exactly between defining a method like this:
def method[A](//...//) {}
or
def method(//...//) {}
Also, is def method[A]
the same as def method[Any]
?
Help would be greatly appreciated.
Upvotes: 1
Views: 79
Reputation: 167921
def method[A]
defines a generic type A
. Used like this, with no refinement, it is a wildcard that can be satisfied by any type. (You can specify that only some subtypes are allowed with syntax like [A <: Foo]
, where Foo
is a class or trait you've defined.)
Why would you want to do this? Most likely, you want a method that returns the same type that it takes as an argument (or some variation thereof--maybe it takes a list of that type and returns an array of that type):
def method[A](a: A): A = ...
Since you don't know anything about A
, it is as generic as Any
.
Now, there's nothing special about A
. You could put anything there, even Any
:
def method[Any](a: Any) ... // Don't do this!
But this would be supremely confusing, because this isn't your standard Any
type that is at the top of the inheritance hierarchy--it's a generic type just like A
, but with a longer name.
If you don't need to use a generic type, omit the [A]
. For example:
def printed[A](a: A): A = { println(a); a } // Generic necessary
def printMe(a: Any) { println(a) } // Not necessary, returns Unit
Upvotes: 7