tags:

views:

87

answers:

2

Is this possible to get:

object test[A](l: Int): List[A] = {
    ...
}

You know what i mean. Is that possible?

+2  A: 

Traits or Objects cannot have constructor parameters, and objects cannot have type parameters.

An object is effectively a singleton instance of a class. Therefore you can't have a generic definition of it, because it has only one name.

Your best option is to define a method within an object which returns the list you want.

MatthieuF
So what would be the best way for generating List of some type?
matiit
@MatthieuF: Traits certainly *may* have type parameters! Objects may not.
Randall Schulz
To clarify: traits can have type parameters, but not constructor parameters. Answer edited
MatthieuF
+4  A: 

Maybe you mean something like

object MyListMaker {
  def test[A](a0: A, n: Int): List[A] = (1 to n).map(_ => a0).toList
}

scala> MyListMaker.test("Fish",7)
res0: List[java.lang.String] = List(Fish, Fish, Fish, Fish, Fish, Fish, Fish)

Only one copy of an object exists; if you want to create a method that does something generic, add the type parameter to the method (not the object).

Rex Kerr
You should have made the method `apply` instead of `test`, which would give a much closer syntax to what was asked.
Daniel
@Daniel - Maybe so. I had trouble figuring out what was being asked, and using `apply` adds an extra wrinkle in understanding why it works. But, yes, with `def apply...` it would just be `MyListMaker("Fish",7)`. I was more worried about making a list of `A`s without actually having any `A`'s.
Rex Kerr