Teapot
Teapot

Reputation: 59

Scala: Create new list of same type

I'm stuck and the solutions Google offered me (not that many) didn't work somehow. It sounds trivial but kept me busy for two hours now (maybe I should go for a walk...).

I've got a list of type XY, oldList: List[XY] with elements in it. All I need is a new, empty List of the same type.

I've already tried stuff like:

newList[classOf(oldList[0])]
newList = oldList.clone()
newList.clear()

But it didn't work some how or takes MutableList, which I don't like. :/

Is there a best (or any working) practice to create a new List of a certain type?

Grateful for any advice, Teapot

P.S. please don't be too harsh if it's simple, I'm new to Scala. :(

Upvotes: 3

Views: 146

Answers (3)

wingedsubmariner
wingedsubmariner

Reputation: 13667

Because empty lists do not contain anything, the type parameter doesn't actually matter - an empty List[Int] is the same as an empty List[String]. And in fact, they are exactly the same object, Nil. Nil has type List[Nothing], and can be upcast to any other kind of List.

In general though when working with types that take type parameters, the type parameter for the old value will be in scope, and it can be used to create a new instance. So a generic method for a mutable collection, where the type parameter matters even if empty:

def processList[T](oldList: collection.mutable.Buffer[T]) = {
  val newList = collection.mutable.Buffer[T]()
  // Do something with oldList and newList
}

Upvotes: 1

om-nom-nom
om-nom-nom

Reputation: 62835

There are probably nicer solutions, but from the top of my head:

def nilOfSameType[T](l: List[T]) = List.empty[T]
val xs = List(1,2,3)
nilOfSameType(xs)
// List[Int] = List()

Upvotes: 1

redeagle47
redeagle47

Reputation: 1377

if you want it to be empty, all you should have to do is:

val newList = List[XY]()

That's really it, as long as I'm understanding your question.

Upvotes: 0

Related Questions