Scala 中的类型定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21223051/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:00:59  来源:igfitidea点击:

Typedef in Scala

scala

提问by Aleksandr Pakhomov

How can I define type in Scala? Like

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

type MySparseVector = [(Int, Double)]

in Haskell or

在 Haskell 或

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

in C++?

在 C++ 中?

I tried

我试过

type MySparseVector = List((Int, Double))

but can't figure how to make it work. If I write this in the beginning of class file I got "Expected class or object definition" error.

但不知道如何使它工作。如果我在类文件的开头写这个,我会收到“预期的类或对象定义”错误。

PS Sorry, I mistyped. I tried to use List[(Int, Double)] in Scala.

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

回答by y?s??la

type MySparseVector = List[(Int, Double)]

Example usage:

用法示例:

val l: MySparseVector = List((1, 1.1), (2, 2.2))

Types have to be defined inside of a class or an object. You can import them afterwards. You can also define them within a package object - no import is required in the same package, and you can still import them into other packages. Example:

类型必须在类或对象内定义。您可以稍后导入它们。您还可以在包对象中定义它们 - 在同一个包中不需要导入,您仍然可以将它们导入到其他包中。例子:

// 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
}