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:


Umar, where did you see that inline classes are coming soon? Or is that just based on the some of the discussions about inline classes starting in 2013? What are inline classes, Implicit conversions between type aliases, Extension Functions on Type Aliases Should only Be Accessable From Similar Types


I guess he is referring to Project Valhalla, which is an experimental branch of OpenJDK, which among other features introduces Value Types. Value Types could then be used to implement features like this or multiple return values.


In this article https://m.habrahabr.ru/company/redmadrobot/blog/351516/