All*_*Han 5 scala type-alias 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)
它不会将您锁定在特定的基础集合中,因此您可以在呼叫站点自由使用最有意义的内容。
| 归档时间: | 
 | 
| 查看次数: | 47 次 | 
| 最近记录: |