【问题标题】:Type Member w/ Implicit类型成员 w/ 隐式
【发布时间】:2016-09-26 21:42:38
【问题描述】:

给定:

// type-class
trait Eq[A]

class MyInt 
object MyInt {
  implicit val myIntEq = new Eq[MyInt] {}
}

sealed trait Something {
  type A 
  implicit val x: Eq[A]
}

case object SomethingImpl extends Something {
  override type A = MyInt
  override implicit val x = MyInt.myIntEq
}

然后,我使用了类型成员的implicit via:

scala> def f(s: Something): Eq[s.A] = {
     |   implicit val x: Eq[s.A] = s.x
     |   x
     | }
f: (s: Something)Eq[s.A]

但是,我的直觉告诉我,必须通过 implicit val ... 将隐式带入范围有点笨拙。

也许我应该在Something 的伴随对象中定义f 函数?

定义这个f函数的标准方法是什么?

【问题讨论】:

  • 你的f函数的例子似乎过于简单了,因为根据目前的信息,我会简单地将它实现为= s.x。
  • 你可以import s.x。
  • @Jasper-M 这是答案,不是评论。

标签: scala implicit


【解决方案1】:

如果你想把某个隐式带入作用域,你通常import它。

def f(s: Something) = {
  import s.x
  ???
}

【讨论】:

  • 是否可以在Something 伴侣中写f?我试过了,object Something { def f(x: Something) = { implicitly[Eq[x.A]]; ??? } },但没有编译。
猜你喜欢
  • 2011-08-28
  • 1970-01-01
  • 2012-11-04
  • 1970-01-01
  • 2023-03-05
  • 2019-02-03
  • 1970-01-01
  • 1970-01-01
  • 2016-12-11
相关资源
最近更新 更多