无形的HList类型扩展了一个共同的特征



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

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的子类型?

更新

我认为联产品可能是一个解决方案

type ST = t1 :+: t2 :+: CNil
fun(Coproduct[ST](5 :: "foo" :: 3 :: HNil)) // compiles
fun(Coproduct[ST](5 :: 3 :: HNil))          // does not compile

使用别名不可能将类型"制作"为任何内容的子类型,别名只是一个新名称。虽然您可以使用共积,但创建一个新的类型类可能更自然:

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

现在,您要编译的行会编译,而您不想编译的行不会。

最新更新