Martijn
Martijn

Reputation: 12102

What is meant by a type that denotes an implicit conversion

The scala language specification, section 7.2 is about implicit scope: It explains that implicit scope are the modules associated in some way with the parts of type T. What the parts of T are is listed below. One of those points is

if T denotes an implicit conversion to a type with a method with argument types T1,…,Tn and result type U, the union of the parts of T1,…,Tn and U;

I can't make head or tails from this. I don't understand how a type T can denote an implicit conversion.

What is meant by this part of the specification of implicit scope?

Upvotes: 5

Views: 86

Answers (2)

Dmytro Mitin
Dmytro Mitin

Reputation: 51658

Here are examples:

trait A
object A {
  implicit def f(a: A): B = null
}

trait B

val b: B = new A {} // compiles

or

trait A

trait B
object B {
  implicit def f(a: A): B = null
}

val b: B = new A {} // compiles

Let T denote an implicit conversion to a type, from A to B (val b: B = new A {}), it denotes the conversion with a method with argument types T1,…,Tn = A and result type U = B. So the parts of T are the union of the parts of A and parts of B. So an implicit can be defined as a member of the companion object of a base class of the parts of T (i.e. A or B).

Upvotes: 1

Mario Galic
Mario Galic

Reputation: 48410

I believe this is referring to the following situation

case class Foo(v: Int)
object Foo {
  implicit def stringToFoo(s: String) = Foo(42)
}

def f[A](v: A)(implicit ev: A => Foo) = ev(v)

f("woohoo")

where the implicit conversion type T = A => Foo, and Foo is the part associated with type parameter A, therefore object Foo becomes part of the implicit scope and stringToFoo implicit conversion is resolved without needing an import.

Upvotes: 5

Related Questions