【问题标题】:Shapeless HList parameter override无形 HList 参数覆盖
【发布时间】:2017-10-03 23:33:45
【问题描述】:

我有一个抽象类,其方法接收 HList 作为参数 (A)。 但是在子类中,我想限制这个 HList (B)

的确切类型

下面的代码不起作用(它没有将(Int :: String :: HNil) 视为HList 的子类。但是如何实现类似的效果呢?

import shapeless.{::, HList, HNil}
import shapeless.syntax.std.tuple._

abstract class A{
  def test[H <: HList](h: H): String
}


class B extends A {
  override def test(h: (Int :: String :: HNil)): String = {
    val a = h(0)
    val b = h(1)
    s"$a -- $b"
  }
}


new B().test(25  :: "testje" ::  HNil)

【问题讨论】:

    标签: scala shapeless hlist


    【解决方案1】:

    即使没有 HLists,这也不是您可以在 Scala 中按原样执行的操作。想象一下尝试做一些更简单的事情

    trait Foo
    trait Bar extends Foo
    
    abstract class A {
      def test[T <: Foo](t: T): String
    }
    
    class B extends A {
      override def test(b: Bar): String = //...
    }
    

    这不起作用,因为B.testA.test 的签名不同。一个有类型参数,而另一个没有。继承要求B 应该能够充当A,但这显然不能在这里发生。

    相反,您可以将类型参数移动到类本身:

    abstract class A[T <: Foo] {
      def test(t: T): String
    }
    
    class B extends A[Bar] {
      override def test(b: Bar): String = //...
    }
    

    这在使用 HLists 时也应该可以正常工作。

    【讨论】:

      猜你喜欢
      • 2020-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-18
      • 2023-03-04
      • 1970-01-01
      相关资源
      最近更新 更多