相关疑难解决方法(0)

存在类型和类型成员

什么有效(A部分​​)

假设我有一个带有类型参数的特征:

trait A[T]
Run Code Online (Sandbox Code Playgroud)

我可以使用存在类型来编写一个方法,该方法将采用A所有具有相同的s 的集合T:

def foo(as: Seq[A[X]] forSome { type X }) = true
Run Code Online (Sandbox Code Playgroud)

请注意,这与以下内容不同:

def otherFoo(as: Seq[A[X] forSome { type X }]) = true
Run Code Online (Sandbox Code Playgroud)

或等效的:

def otherFoo(as: Seq[A[_]]) = true
Run Code Online (Sandbox Code Playgroud)

在这些情况下,存在主义的范围在里面Seq,所以As可以有不同的Ts.使用我的原始foo(存在范围Seq),以下是好的:

foo(Seq(new A[Int] {}, new A[Int] {}))
Run Code Online (Sandbox Code Playgroud)

但是使类型参数不同并且不能编译:

scala> foo(Seq(new A[Int] {}, new A[String] {}))
<console>:10: error: type mismatch;
 found   : Seq[A[_ >: java.lang.String with Int]]
 required: Seq[A[X]] forSome { type X } …
Run Code Online (Sandbox Code Playgroud)

generics types scala existential-type type-members

12
推荐指数
1
解决办法
1815
查看次数

类型安全的矩形多维数组类型

你如何在Scala中表示矩形的二维(或多维)数组数据结构?

也就是说,每行具有相同的长度,在编译时验证,但维度是在运行时确定的?

Seq[Seq[A]] 具有所需的接口,但它允许用户提供"参差不齐"的阵列,这可能导致运行时故障.

Seq[(A, A, A, A, A, A)] (和类似的)确认长度是相同的,但它也强制在编译时指定这个长度.

示例界面

这是我的意思的示例界面(当然,内部维度不必是元组;它可以指定为列表或其他类型):

// Function that takes a rectangular array
def processArray(arr : RectArray2D[Int]) = {
    // do something that assumes all rows of RectArray are the same length
}

// Calling the function (OK)
println(processArray(RectArray2D(
    ( 0,  1,  2,  3),
    (10, 11, 12, 13),
    (20, 21, 22, 23)
)))
// Compile-time error
println(processArray(RectArray2D(
    ( 0,  1,  2,  3),
    (10, 11, 12),
    (20, 21, 22, 23, …
Run Code Online (Sandbox Code Playgroud)

arrays collections types scala multidimensional-array

7
推荐指数
1
解决办法
577
查看次数