What is meant by a type that denotes an implicit conversion
Asked Answered
B

2

5

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?

Blackguard answered 14/2, 2020 at 15:8 Comment(0)
H
5

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.

Homozygote answered 14/2, 2020 at 15:24 Comment(1)
I don't think this rule is used here; A => Foo is Function1[A, Foo] so its parts include Foo by the rule for parametrized types. (I added my own answer.)Lapidify
U
1

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).

Uncanny answered 6/7, 2020 at 12:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.