Question

Let's say I have a trait, Foo and this trait takes a generic type Bar so that the definition for Foo would look exactly like

trait Foo[C <: Bar] {
    def updateState(state : C) : C;
}

, and I have several classes action1, action2, action3 ... action9 that extend Foo.

Now, let's say I want to explicitly initialize a 2d array of these actions.

I've tried

Array[Foo[Bar]](
Array(new action1, new action2),
Array(new action2, new action3)...
) 
Array[Foo[Bar]](
Array[Foo[Bar]](new action1, new action2),
Array[Foo[Bar]](new action2, new action3)...
) 

and most of the permutations of adding the [Foo[Bar]] with bar [Foo] without bar, making the main array Array[Array[Foo[Bar]]] etc.

I've found a solution to the problem by using

Array.ofDim[Foo[Bar]](size1, size2, size3)

and manually initializing each dimension but I'd like to know if there is some way to explicitly initialize a 2d array of a type that implements a generic trait...yes, I know there are about 3 use cases for doing this (not really but it's not very common) so an answer like "Why are you doing this?" or "There are better ways of bla bla bla" won't be too impacting on me.

Was it helpful?

Solution

If you can define relation between index of item and instance of class, than use:

tabulate[T](n1: Int, n2: Int)(f: (Int, Int) ⇒ T)

Example:

Array.tabulate(5, 5) {
  case (i, j) => new action(i, j)
}

Update:

scala> :paste
// Entering paste mode (ctrl-D to finish)    
trait Bar
class Foo[C <: Bar]

Array.tabulate(5, 5) {
  case (i, j) => new Foo[Bar]()
}

// Exiting paste mode, now interpreting.

defined trait Bar
defined class Foo
res1: Array[Array[Foo[Bar]]] = Array(Array(Foo@5e1c4451, Foo@11c9521c, Foo@382db563, Foo@40df9365, Foo@1645ed29), Array(Foo@48d52a2b, Foo@22c39268, Foo@55c0fbac, Foo@70cb052f, Foo@20c18a83), Array(Foo@26caf42, Foo@2d66174c, Foo@98395dd, Foo@1de3e50c, Foo@5cd28628), Array(Foo@165dbb4, Foo@463b0723, Foo@4d51aeda, Foo@2dae91de, Foo@1fea9d40), Array(Foo@63f9e51e, Foo@2b3147d9, Foo@30640db6, Foo@78c0408b, Foo@15cda39c))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top