Arrays 在scala中定义二维数组
我必须调用一个定义为 Scala中的foo(Seq[Seq[Int]]) 我已将Int数组定义为:Arrays 在scala中定义二维数组,arrays,scala,Arrays,Scala,我必须调用一个定义为 Scala中的foo(Seq[Seq[Int]]) 我已将Int数组定义为: var myArray = Array.ofDim[Int](N,N) 我正在呼叫foo(myArray) 但是,我得到了一个错误: type mismatch; found : Array[Array[Int]] required: Seq[Seq[Int]] 如果我尝试将数组定义为 var myArray = Seq[Seq[Int]](N,N) 我得到这个错误: type mi
var myArray = Array.ofDim[Int](N,N)
我正在呼叫foo(myArray)
但是,我得到了一个错误:
type mismatch; found : Array[Array[Int]] required: Seq[Seq[Int]]
如果我尝试将数组定义为
var myArray = Seq[Seq[Int]](N,N)
我得到这个错误:
type mismatch; found : Int required: Seq[Int]
为什么呢?我挣扎了两个多小时,想找出问题所在,但我不知道
有人能帮我吗?如果你想要一个嵌套的seq:
seq[seq[Int]]
> var s = Seq(Seq(1, 2),Seq(3, 4))
> s(0)(1)
> 2
如果需要嵌套的seq:
seq[seq[Int]]
> var s = Seq(Seq(1, 2),Seq(3, 4))
> s(0)(1)
> 2
嗯,
Array
不是Seq
的子类,因此您会得到错误
您可以将Array[Array[Int]]
转换为Seq[Seq[Int]]
如下:
val myArray = Array.ofDim[Int](N,N) //use vals if you can, arrays are mutable
val mySeq = myArray.map(_.toSeq).toSeq //convert all inner Arrays to Seq and then the outer array to Seq
foo(mySeq)
请记住,
Array
是可变的,而Seq
不是。好吧,Array
不是Seq
的子类,因此会出现错误
Welcome to Scala version 2.10.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_45).
Type in expressions to have them evaluated.
Type :help for more information.
scala> val N = 10
N: Int = 10
scala> val s = Seq.fill(N, N)(0)
s: Seq[Seq[Int]] = List(List(0, ... 0))
scala>
您可以将Array[Array[Int]]
转换为Seq[Seq[Int]]
如下:
val myArray = Array.ofDim[Int](N,N) //use vals if you can, arrays are mutable
val mySeq = myArray.map(_.toSeq).toSeq //convert all inner Arrays to Seq and then the outer array to Seq
foo(mySeq)
请记住,Array
是可变的,而Seq
不是可变的
Welcome to Scala version 2.10.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_45).
Type in expressions to have them evaluated.
Type :help for more information.
scala> val N = 10
N: Int = 10
scala> val s = Seq.fill(N, N)(0)
s: Seq[Seq[Int]] = List(List(0, ... 0))
scala>
或
或
另外,方法
制表使用函数初始化值;比如说
Seq.tabulate(2,2)( (_,_) => 0 )
Seq[Seq[Int]] = List(List(0, 0), List(0, 0))
及
另外,方法制表使用函数初始化值;比如说
Seq.tabulate(2,2)( (_,_) => 0 )
Seq[Seq[Int]] = List(List(0, 0), List(0, 0))
及
谢谢史蒂文。。。不,我只是想定义一下。我不想在它里面有任何值…好的。首先是定义(Seq[Seq[T]])。再次感谢。然而,正如我在问题中提到的,如果我这样定义它,我会得到一个错误。我还需要把它定义为。。。不,我只是想定义一下。我不想在它里面有任何值…好的。首先是定义(Seq[Seq[T]])。再次感谢。然而,正如我在问题中提到的,如果我这样定义它,我会得到一个错误。我还需要将其定义为2D