[英]How to use a type alias to define a type constructor
Let's say I have some code that uses List假设我有一些使用 List 的代码
def processList(input: List[Int]): List[Int]
I want to replace list with other collection types, like Vector.我想用其他集合类型替换列表,比如 Vector。
Is there a way to define a type constructor so that I can write something like有没有办法定义类型构造函数,以便我可以编写类似的东西
type SomeCollection[_] = List[_]
def processList(input: SomeCollection[Int]): SomeCollection[Int]
Now I have written processList in terms of SomeCollection.现在我已经根据 SomeCollection 编写了 processList。 To change SomeCollection to Vector, I just change the type alias, and everywhere in the codebase where I use SomeCollection, I now use Vector.要将 SomeCollection 更改为 Vector,我只需更改类型别名,并且在代码库中使用 SomeCollection 的任何地方,我现在都使用 Vector。 Like so:像这样:
type SomeCollection[_] = Vector[_]
def processList(input: SomeCollection[Int]): SomeCollection[Int]
This way, I only need to change the codebase in one place instead of everywhere.这样,我只需要在一个地方而不是到处更改代码库。
I do not want to write我不想写
type SomeIntCollection = List[Int]
because I have connected the collection to Int type.因为我已将集合连接到 Int 类型。
Is there a way?有办法吗?
You're pretty close, this can be done along the lines of你已经很接近了,这可以按照以下方式完成
type SomeCollection[A] = List[A]
def processList(input: SomeCollection[Int]): SomeCollection[Int] = input.map(_+1)
However, there's better ways to describe the abstraction.但是,有更好的方法来描述抽象。 In the cats
library, there are a variety of typeclasses designed to abstract over the type of operation you want to perform.在cats
库中,有多种类型类旨在抽象出您想要执行的操作类型。 The above with cats would look something like上面的猫看起来像
import cats._
import cats.implicits._
def process[F[_]: Functor](input: F[Int]): F[Int] = input.map(_+1)
It doesn't lock you into a specific underlying collection, so you're free to use whatever makes the most sense at the call site.它不会将您锁定在特定的基础集合中,因此您可以自由使用呼叫站点上最有意义的任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.