【问题标题】:How to retrieve the companion object from the type如何从类型中检索伴随对象
【发布时间】:2014-10-10 15:22:10
【问题描述】:

我想写一个泛型方法,我需要从类型中检索伴随对象(尤其是apply方法)。

[update]X是一个case类,所以伴生对象有一个apply方法。

例如:def f[X]() = X.apply("42")

【问题讨论】:

  • X 是完全通用的吗?如果是集合,那么.companion方法在GenTraversable中实现
  • 更新后,X 是一个案例类
  • 那么尤金的第二个答案是否适用?
  • 是的,但是隐式很麻烦……

标签: scala


【解决方案1】:

没有通用的解决方案,也没有什么限制伴随对象具有应用方法。它可以是伴侣而不应用。在这种情况下,我建议使用类型类模式。

  trait CompanionWithApply[T] {
    def apply(s: String): T
  }

  class X(s: String)
  object X extends CompanionWithApply[X] {
    def apply(s: String): X = new X(s)
  }

  class Y(s: String)
  object Y extends CompanionWithApply[Y]{
    def apply(s: String): Y = new Y(s)
  }

  implicit val XCompanion = X
  implicit val YCompanion = Y

  def f[T: CompanionWithApply] = implicitly[CompanionWithApply[T]].apply("42")

  println(f[X])
  println(f[Y])

【讨论】:

  • 不错,但是如果 X 和 Y 是 case 类,我们需要复制 apply 方法……
  • 你不需要介绍implicit vals。只需使用implicit 作为object 的修饰符。
【解决方案2】:

另一个小得多的解决方案,但你 X,Y 必须是案例类

  case class X(s: String)
  case class Y(s: String)

  implicit def xConstruct = X
  implicit def yConstruct = Y

  def f[T](implicit construct: (String) => T) = construct("abc")

  println(f[X])
  println(f[Y])

【讨论】:

  • 有没有办法避免声明隐含?
猜你喜欢
  • 1970-01-01
  • 2017-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多