A special method: `operator fun usedAs(): SomeType...
# language-proposals
e
A special method:
operator fun usedAs(): SomeType
When the code is compiled, this method is automatically called if it's used as a parameter in that type. That might be a bit confusing, let me elaborate.
Copy code
operator fun String.usedAs(): URL = URL(this)
And then the user can use String in place of URL in method call and constructors. Then the compiler can desugar it to the method call. Though since now you can't really have two methods with the same name, I would make it something more like
Copy code
@Converter(URL::class)
fun asURL(): URL = //...
f
Copy code
interface I
class A : I
class B : I

operator fun String.usedAs(): A = TODO()
operator fun String.usedAs(): B = TODO()

fun f(i: I) { TODO() }

fun main() {
    f("") // A or B? ๐Ÿค”
}
This is the same as Rust's
into
and it often leads to the infamous turbo-fish. If anything, then it should work like Rust's impl.
Copy code
interface I
class A : I
class B : I

operator fun String.into(): A = TODO()
operator fun String.into(): B = TODO()

fun f(i: I) { TODO() }
fun a(a: A) { TODO() }
fun b(b: B) { TODO() }

fun main() {
  f("".into()) // compile error
  f("".into<A>()) // ๐Ÿ‘
  a("".into()) // ๐Ÿ‘
  b("".into()) // ๐Ÿ‘
}
e
I mean you could always throw ambiguity and ask for explicit typing ._.
Or since you can't really have two methods with the same name but return different things, use the annotation system as I said in the edit,
f
Yeah, that's exactly what Rust does (turbo-fish). See example above.
e
That makes sense, though my main point here is to allow for the
.into()
part to be skipped entirely, like an implicit type coercion.
f
It basically is a generic implementation of the manually written
to*
methods that often end up being wild. This way Java interop could also be ensured. An
into(): A
would turn to a
toA()
in Java.
e
And it only needs to be specified when it's ambiguous
Yeah, or use annotations, as I mentioned in the edit.
f
I got that, but modern languages (that includes Kotlin) never perform auto-conversions. It's frowned upon. It can surely be asked for, but chances are slim that it will be considered. However, this request is useful even without this. The annotation would be on the declaration site and not the call site, making it implicit again. Same reasoning, makes programs hard to reason about.
e
Hm, maybe a code block which allows implicit conversion for all methods within the block?
Something like
Copy code
implicitConversion {
    somethingWithURL("<http://example.com|example.com>")
}