I want to achieve this:
implicit def aConvertable(obj: A): B = new B(obj)
implicit def aConvertableWithoutB[T <: A without B](obj: T): C = new C(obj)
What is the correct way to say: "A without B"?
I'm assuming that B is a subtype of A. The trick is to introduce an implicit "AllowedConversion" trait that works for all A's, and then two implicit instances for B that have the same type, so that they're ambiguous for B:
object Foo {
trait A
class B(a: A) extends A
class C(a: A)
class AllowedConversion[T]
implicit def allowedForAs[T<:A] = new AllowedConversion[T]
implicit def contradictoryForBs[T <: B] = new AllowedConversion[T]
implicit def contradictoryForBs2[T <: B] = new AllowedConversion[T]
implicit def aConvertable(obj: A): B = new B(obj)
implicit def aConvertableWithoutB[T <: A](obj: T)(implicit allowed: AllowedConversion[T]): C = new C(obj)
// error!
// new B(new A{}):C
// ok!
new A{}:C
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.