Explicit cast for type aliases


First of all: I recognise that typealias is just name for the same type and real casting would not be the case there, but I think following behaviour would be pretty handy :

Feature proposal

Ability to force type alias cast when assigning to aliased/compatible type. Probably adding new keyword would be good idea.


Here is an example of what I’m thinking about:

forced typealias UserId = UUID
// .... //
val userId: UserId = ...
val someOtherId = userId // <- compile error here

And if we really know what we are doing:

val someOtherId = userId as UUID

Real use case

I have two related entities, lets name them Parent and Child.
Parent is identified by Long id value and so is child of parent so I have method to retrieve them with signature:

fun findChildren(parentId: ParentId, childId: ChildId)

where ParentId and ChildId are aliases of Long.

It is pretty easy to make there mistake in order of arguments and pass parentId as childId and vice versa.

I now I can wrap both ids in some value class or other pattern, but language support would make this problem just disappear.


Inline classes are coming soon, probably. You can just wrap a single value without overhead in runtime.


Sounds like the feature I’m looking for, thanks for the info :wink: