Scala 中的类型定义 [英] Typedef in Scala

查看:39
本文介绍了Scala 中的类型定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I define type in Scala? Like

type MySparseVector = [(Int, Double)]

在 Haskell 或

in Haskell or

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

在 C++ 中?

我试过了

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 抱歉,我打错了.我尝试在 Scala 中使用 List[(Int, Double)].

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

推荐答案

type MySparseVector = List[(Int, Double)]

示例用法:

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
}

这篇关于Scala 中的类型定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆