4

我有一些基于无形 HList 的类型:

type t1 = Int :: String :: Int :: HNil
type t2 = String :: String :: Int :: HNil

我想ST为所有这些定义一个超类型的密封特征,这样,如果我有以下功能:

def fun(x:ST) = …

以下是有效的:

fun(5 :: "foo" :: 3 :: HNil)       // It is a t1
fun("foo" :: "bar" :: 42 :: HNil)  // It is a t2

但以下内容无法编译:

fun(5 :: 3 :: HNil)

我如何定义t1t2作为子类型ST

更新

我认为 Coproducts 可能是一个解决方案

type ST = t1 :+: t2 :+: CNil

fun(Coproduct[ST](5 :: "foo" :: 3 :: HNil)) // compiles
fun(Coproduct[ST](5 :: 3 :: HNil))          // does not compile
4

1 回答 1

3

不可能使用别名将类型“制作”为任何事物的子类型,别名只是一个新名称。虽然您可以使用副产品,但创建一个新的类型类可能更自然:

import shapeless._

type t1 = Int :: String :: Int :: HNil
type t2 = String :: String :: Int :: HNil

trait Funnable[A]

implicit object t1Funnable extends Funnable[t1]
implicit object t2Funnable extends Funnable[t2]

def fun[A: Funnable](x: A) = x

现在你想编译的行会,你不想编译的行不会。

于 2014-02-25T23:30:49.857 回答