Skip to content

Make convert available without import #11786

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 19, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class CompletionTest {

@Test def completionFromScalaPackage: Unit = {
code"class Foo { val foo: Conv${m1} }".withSource
.completion(m1, Set(("Conversion", Class, "class and object Conversion")))
.completion(m1, Set(("Conversion", Class, "scala.Conversion")))
}

@Test def completionFromScalaPackageObject: Unit = {
Expand Down
7 changes: 3 additions & 4 deletions library/src/scala/Conversion.scala
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@ package scala
abstract class Conversion[-T, +U] extends Function1[T, U]:
/** Convert value `x` of type `T` to type `U` */
def apply(x: T): U
object Conversion:

extension [T](x: T)
/** `x.convert[U]` converts a value `x` of type `T` to type `U` */
def convert[U](using c: Conversion[T, U]) = c(x)
extension (x: T)
/** `x.convert` converts a value `x` of type `T` to type `U` */
def convert = this(x)
6 changes: 4 additions & 2 deletions tests/pos/convert.scala
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import Conversion.convert
import java.util.Date

given Conversion[String, Int] = _.length
given Conversion[Int, String] = _.toString
given Conversion[Int, Date] = new Date(_)

def f(x: String): Int = x.convert
def g(x: Int): String = x.convert[String]
def g(x: Int): String = x.convert
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This won't work if there are two Conversion[Int, Y] in scope for two different Ys.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It does with a suitable type ascription, see updated test.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sjrd Looks like @rjolly is right. Do you agree?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, apparently it works, indeed.

def h(x: Int): Date = x.convert