Skip to main content
 首页 » 编程设计

scala之Scala 中的类型定义

2024年12月31日5lhb25

如何在 Scala 中定义类型?
喜欢

type MySparseVector = [(Int, Double)] 

在 Haskell 或
typedef MySparseVector = std::list<std::pair(int, double)>>  

在 C++ 中?

我试过
type MySparseVector = List((Int, Double)) 

但无法弄清楚如何使其工作。如果我在类文件的开头写这个,我会收到“预期的类或对象定义”错误。

PS对不起,我打错了。我尝试在 Scala 中使用 List[(Int, Double)] 。

请您参考如下方法:

type MySparseVector = List[(Int, Double)] 

用法示例:
val l: MySparseVector = List((1, 1.1), (2, 2.2)) 

类型必须在类或对象内部定义。您可以稍后导入它们。您还可以在包对象中定义它们 - 在同一个包中不需要导入,您仍然可以将它们导入到其他包中。例子:
// file: mypackage.scala 
package object mypackage { 
  type MySparseVector = List[(Int, Double)] 
} 
 
//in the same directory: 
package mypackage 
// no import required 
class Something { 
  val l: MySparseVector = Nil 
} 
 
// in some other directory and package: 
package otherpackage 
import mypackage._ 
class SomethingElse { 
  val l: MySparseVector = Nil 
}