[英]How to use a type alias to define a type constructor
假设我有一些使用 List 的代码
def processList(input: List[Int]): List[Int]
我想用其他集合类型替换列表,比如 Vector。
有没有办法定义类型构造函数,以便我可以编写类似的东西
type SomeCollection[_] = List[_]
def processList(input: SomeCollection[Int]): SomeCollection[Int]
现在我已经根据 SomeCollection 编写了 processList。 要将 SomeCollection 更改为 Vector,我只需更改类型别名,并且在代码库中使用 SomeCollection 的任何地方,我现在都使用 Vector。 像这样:
type SomeCollection[_] = Vector[_]
def processList(input: SomeCollection[Int]): SomeCollection[Int]
这样,我只需要在一个地方而不是到处更改代码库。
我不想写
type SomeIntCollection = List[Int]
因为我已将集合连接到 Int 类型。
有办法吗?
你已经很接近了,这可以按照以下方式完成
type SomeCollection[A] = List[A]
def processList(input: SomeCollection[Int]): SomeCollection[Int] = input.map(_+1)
但是,有更好的方法来描述抽象。 在cats
库中,有多种类型类旨在抽象出您想要执行的操作类型。 上面的猫看起来像
import cats._
import cats.implicits._
def process[F[_]: Functor](input: F[Int]): F[Int] = input.map(_+1)
它不会将您锁定在特定的基础集合中,因此您可以自由使用呼叫站点上最有意义的任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.