如何在Scala中编写数据类型的简写

时间:2016-06-09 00:28:59

标签: scala

如何为数据类型写简写? 例如。 让我们说,而不是List[Integer],我宁愿输入Integers

而不是

def processNumbers(input:List[Integer]):List[Integer] = ...

def processNumbers(input:Integers):Integers = ...

这可能吗?

由于

1 个答案:

答案 0 :(得分:4)

是的,您可以使用type alias

执行此操作
type Integers = List[Int]  // scala.Int is preferred over java.lang.Integer

话虽如此,这对他们来说并不是一个好用的。 List[Int]对其他scala开发人员非常清楚,因为您的类型Integers没有提供额外信息,因此会降低代码随时间的可读性。

使用类型别名可以提高代码的可读性,但类似

type UserId = Int
def processUsers(ids: List[UserId]): Foo

在这种情况下,它为读者提供了额外的信息

def processUsers(ids: List[Int]): Foo

使用这种类型别名还可以让您通过将类型别名更改为value class来逐步使代码更加类型安全。

case class UserId(value: Int) extends AnyVal

您不需要更改已经拥有“UserId”的任何内容的方法签名,但这会让编译器帮助您确保不执行类似

的操作
val ids: List[Int] = getBlogPostIds()
val foo = processUsers(ids) // Oops, those Ints are for blog posts, not users

使用值类方法,这样的错误会成为编译器错误。普遍使用它在编写正确的代码时增加了很多指导。

val ids: List[BlogPostId] = getBlogPostIds
val foo = processUsers(ids) // Compile error; BlogPostId != UserId