Skip to content

Commit c3ea17d

Browse files
committed
Add section on implicit conversions
1 parent 9bb87f0 commit c3ea17d

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
---
2+
layout: doc-page
3+
title: "Restrictions to Implicit Conversions"
4+
---
5+
6+
Previously, an implicit value of type `Function1`, or any of its subtypes
7+
could be used as an implicit conversion. That is, the following code would compile
8+
even though it probably masks a type error:
9+
10+
implicit val m: Map[String, Int] = Map(1 -> "abc")
11+
12+
val x: String = 1 // scalac: assigns "abc" to x
13+
// Dotty: type error
14+
15+
By contrast, Dotty only considers _methods_ as implicit conversions, so the
16+
`Map` value `m` above would not qualify as a conversion from `String` to `Int`.
17+
18+
To be able to express implicit conversions passed as parameters, `Dotty`
19+
introduces a new type
20+
21+
abstract class ImplicitConverter[-T, +U] extends Function1[T, U]
22+
23+
Implicit values of type `ImplicitConverter[A, B]` do qualify as implicit
24+
conversions. It is as if there was a global implicit conversion method
25+
26+
def convert[A, B](x: A)(implicit converter: ImplicitConverter[A, B]): B =
27+
converter(x)
28+
29+
(In reality the Dotty compiler simulates the behavior of this method directly in
30+
its type checking because this turns out to be more efficient).
31+
32+
In summary, previous code using implicit conversion parameters such as
33+
34+
def useConversion(implicit f: A => B) {
35+
val y: A = ...
36+
val x: B = a // error under Dotty
37+
}
38+
39+
is no longer legal and has to be rwritten to
40+
41+
def useConversion(implicit f: ImplicitConverter[A, B]) {
42+
val y: A = ...
43+
val x: B = a // OK
44+
}
45+
46+
47+
48+

docs/sidebar.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ sidebar:
4747
url: docs/reference/changed/type-inference.md
4848
- title: Implicit Resolution
4949
url: docs/reference/changed/implicit-resolution.md
50+
- title: Implicit Conversions
51+
url: docs/reference/changed/implicit-conversions.md
5052
- title: Vararg Patterns
5153
url: docs/reference/changed/vararg-patterns.md
5254
- title: Dropped Features

0 commit comments

Comments
 (0)