Hi :wave: I'm coming from the Swift world and ther...
# announcements
d
Hi 👋 I'm coming from the Swift world and there are a set of protocols over there that called
ExpressibleByXXXXLiteral
, so you can create a type and if you pass the correct type of literal as an argument the compiler will automatically lift that literal into the correct type. For instance one nice thing in Kotlin would be to be able to express an
inline class
as a literal without having to explicitly initialize a type at the callsite:
Copy code
inline class UserID(val value: Int) {}

data class User(val userID: UserID) {}

// would love to be able to do this
val user = User(5)

// instead i have to do this
val user = User(UserID(5))
r
This is exactly what inline classes are meant to prevent. Seems like a typealias is better suited for what you want, but you lose the compile time guarantees then.
âž• 7
d
This post doesn't properly explain what I meant, the other thread gives better examples and is hopefully more clear. It doesn't lose the compile time guarantees, its just syntax sugar 🙂
a
You can just create an invoke extension operator on User which utilizes an Int. If you really wish
Or a secondary constructor
d
Ya someone brought that up in the other thread as well and I addressed it there, but the difference is that the new function would in fact let you pass other incorrect values that wouldn't be possible with compiler literal-lifting
c
I’m late to the party, but could also accomplish the same with a typealias:
Copy code
typealias UserID = Int

data class User(val userID: UserID)

val user = User(5)
d
Ya absolutely Christian, but as some other people pointed out in the other thread you would lose the type-safety benefits that inline classes give you 😞