如何使用类型别名来定义类型构造函数
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)
它不会将您锁定在特定的基础集合中,因此您可以自由使用在调用站点最有意义的任何内容。
假设我有一些使用 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)
它不会将您锁定在特定的基础集合中,因此您可以自由使用在调用站点最有意义的任何内容。