簡體   English   中英

如何使用類型別名來定義類型構造函數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM