如何使用类型别名定义类型构造函数 [英] How to use a type alias to define a type constructor

查看:216
本文介绍了如何使用类型别名定义类型构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一些使用列表的代码

Let's say I have some code that uses List

def processList(input: List[Int]): List[Int]

我想用其他集合类型(例如Vector)替换列表.

I want to replace list with other collection types, like 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]

现在我已经按照SomeCollection编写了processList.要将SomeCollection更改为Vector,只需更改类型别名,在使用SomeCollection的代码库中的任何地方,我现在都使用Vector.像这样:

Now I have written processList in terms of SomeCollection. To change SomeCollection to Vector, I just change the type alias, and everywhere in the codebase where I use SomeCollection, I now use 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.

我不想写

type SomeIntCollection = List[Int]

因为我已将集合连接到Int类型.

because I have connected the collection to Int type.

有办法吗?

推荐答案

您非常接近,可以按照以下步骤进行操作

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)

但是,有更好的方法来描述抽象.在cats库中,有多种类型类设计用于抽象您要执行的操作的类型.上面的猫看起来像

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. 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.

这篇关于如何使用类型别名定义类型构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆