Where to put implicit value to enable implicit conversion about singleton type

182 views Asked by At

Consider the case:

class T[A0, B0](val a: A0, val b: B0)
class A
class B(val a: A) {
  b =>
  implicit def t: T[a.type, b.type] = new T(a, b)
}
val b = new B(new A)
val t1 = implicitly[T[b.a.type, b.type]]// can't compile, I want t1 = b.t

How to enable implicit conversion of singleton type parameter?

Consider the trade-off:

class T[A0, B0, H0](val a: A0, val b: B0)
class A
class B(val a: A) {
  b =>
  class H
  object H{
    implicit def t: T[a.type, b.type, b.H] = new T(a, b)        
  }
}
val a = new A
val b = new B(a)
val t1 = implicitly[T[b.a.type, b.type, b.H]]

That works, but looks ugly. Is there any good method?

1

There are 1 answers

0
蘇哲聖 On BEST ANSWER

We can just add import b._.

class T[A0, B0](val a: A0, val b: B0)
class A
class B(val a: A) {
  b =>
  implicit def t: T[a.type, b.type] = new T(a, b)
}
val b = new B(new A)
import b._
val t1 = implicitly[T[b.a.type, b.type]]