初学者:Scala 2.10 中的 Scala 类型别名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15783837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Beginner: Scala type alias in Scala 2.10?
提问by Tony
Why does this code fail to compile with the error: not found: value Matrix? From the documentation and some (possibly out of date) code examples this should work?
为什么此代码无法编译并显示错误:未找到:值矩阵?从文档和一些(可能已经过时的)代码示例来看,这应该有效吗?
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)
)
}
回答by Régis Jean-Gilles
Matrixdenotes a type, but you are using it as a value.
Matrix表示一种类型,但您将其用作值。
When you do List(1, 2, 3), you are actually calling List.apply, which is a factory method for List.
当您这样做时List(1, 2, 3),您实际上是在调用List.apply,这是List.
To fix your compiling error, you can define your own factories for Matrixand Row:
要修复编译错误,您可以为Matrixand定义自己的工厂Row:
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)
)
}
回答by korefn
From thisarticle you have.
从这篇文章你有。
Note also that along with most of the type aliases in package scala comes a value alias of the same name. For instance, there's a type alias for the List class and a value alias for the List object.
还要注意,与包 scala 中的大多数类型别名一起出现的是同名的值别名。例如,List 类有一个类型别名,List 对象有一个值别名。
A solution to the problem translates to:
该问题的解决方案转化为:
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))
}

