https://kotlinlang.org logo
#language-proposals
Title
# language-proposals
e

Eric Ou

08/04/2022, 11:08 AM
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

Fleshgrinder

08/04/2022, 11:12 AM
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

Eric Ou

08/04/2022, 11:14 AM
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

Fleshgrinder

08/04/2022, 11:15 AM
Yeah, that's exactly what Rust does (turbo-fish). See example above.
e

Eric Ou

08/04/2022, 11:16 AM
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

Fleshgrinder

08/04/2022, 11:16 AM
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

Eric Ou

08/04/2022, 11:16 AM
And it only needs to be specified when it's ambiguous
Yeah, or use annotations, as I mentioned in the edit.
f

Fleshgrinder

08/04/2022, 11:17 AM
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

Eric Ou

08/04/2022, 11:19 AM
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>")
}
6 Views