Gal
Gal

Reputation: 5416

How to create a List of objects (i.e. singletons) in Scala?

suppose I have the following code

trait T

object O extends T

Now suppose I want to create a List[T] of size 10, that is populated by O. In other words, the list should look like (O, O, O,..., O).

Trying to do the usual Scala way of (1 until 10) map (x => O) toList creates a List[O.type].

Thanks.

Upvotes: 1

Views: 963

Answers (2)

Nicolas
Nicolas

Reputation: 24769

The issue is that scala inferred the most specific type. In you case, the specific type of the O object: O.type. So you need to precise the type.

By the way, tt's not the scala way to do it, it's better to do:

List.fill(10)(O)

But it won't produce a List[T] either. So you need to do:

List.fill[T](10)(O)

Upvotes: 4

Michał Kosmulski
Michał Kosmulski

Reputation: 10020

Specify your type explicitly:

val l: List[T] = (1 until 10) map (x => O) toList

Upvotes: 3

Related Questions