2

Is this possible to get:

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

You know what i mean. Is that possible?

2 Answers 2

4

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).

Sign up to request clarification or add additional context in comments.

2 Comments

You should have made the method apply instead of test, which would give a much closer syntax to what was asked.
@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 As without actually having any A's.
2

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.

3 Comments

So what would be the best way for generating List of some type?
Traits certainly may have type parameters! Objects may not.
To clarify: traits can have type parameters, but not constructor parameters. Answer edited

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.