初学者:Scala 2.10中的Scala类型别名?

Ton*_*ony 15 scala

为什么这段代码无法使用错误编译:找不到:值矩阵?从文档和一些(可能是过时的)代码示例,这应该工作?

object TestMatrix extends App{  
type Row = List[Int]
type Matrix = List[Row]


val m = Matrix( Row(1,2,3),
                Row(1,2,3),
                Row(1,2,3)
              )


}
Run Code Online (Sandbox Code Playgroud)

Rég*_*les 49

Matrix 表示类型,但您将其用作值.

当你这样做时List(1, 2, 3),你实际上正在调用List.apply,这是一种工厂方法List.

为了解决您的编译错误,您可以定义自己的工厂进行MatrixRow:

object TestMatrix extends App{  
  type Row = List[Int]
  def Row(xs: Int*) = List(xs: _*)

  type Matrix = List[Row]
  def Matrix(xs: Row*) = List(xs: _*)

  val m = Matrix( Row(1,2,3),
      Row(1,2,3),
      Row(1,2,3)
      )
}
Run Code Online (Sandbox Code Playgroud)

  • 只是一个小注意事项,如果您明确指定工厂函数的返回类型(即`def Matrix(xs:Row*):Matrix = List(xs:_*)`),您(可能显然)将帮助编译器/类型检查器将结果看作"矩阵"而不是"列表[行]".当然,将`Matrix`定义为具有与所示`Matrix`工厂方法相同的`apply`方法的对象也是有效的. (2认同)

kor*_*efn 5

这个文章你.

另请注意,scala包中的大多数类型别名都带有同名的别名.例如,List类的类型别名和List对象的值别名.

该问题的解决方案转化为:

object TestMatrix extends App{  
  type Row = List[Int]
  val Row = List
  type Matrix = List[Row]
  val Matrix = List

  val m = Matrix( Row(1,2,3),
                  Row(1,2,3),
                  Row(1,2,3))
}
Run Code Online (Sandbox Code Playgroud)

  • 虽然这是该问题的通用解决方案,但这里不合适,因为类型别名修复了类型参数(到"Int"和"Row").例如,你的代码允许做`Matrix("aze",123)`(返回一个`List [Any]`,它显然不是**与'Matrix`相同的类型),这肯定不是预期的行为. (12认同)