Kevin Meredith Kevin Meredith - 2 months ago 14
Scala Question

Type Member w/ Implicit

Given:

// 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
}


Then, I used the type member's
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]


However, my instincts tell me that it's somewhat clumsy to have to bring the implicit into scope via
implicit val ...
.

Perhaps I should define the
f
function within the
Something
's companion object?

What's the standard way to define this
f
function?

Answer

If you want to bring a certain implicit into scope, you usually import it.

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