I have a question about inline classes. The origin...
# language-proposals
c
I have a question about inline classes. The original announcement states that:
Inline classes are similar to type aliases, but they are not assignment-compatible with the underlying value type, so you cannot assign a String to a variable of type Name, and vice versa.
I'm wondering about the
Name
to
String
conversion part, i.e. let's say we have:
Copy code
inline class Name(val value: String)
val name = Name("Jerzy")

// old API that still uses raw String
fun greet(val name: String)

// the way we'd call the method with Name
greet(name.value)
I'm curious what are the negative aspects of automatic unwrapping, i.e. allowing the
greet(name)
call? I can't think of anything being terribly broken by this change, and it would allow gradual migration from bunch of
String
params to wrapped classes.
a
So you're suggesting limited type coercion for inline classes? I'm opposed to it. What happens if the inline class doesn't have a
value
property or that property is private?
k
What's the point of inline classes then? Eg. in the case of
UInt
its value interpreted as an
Int
isn't really meaningful.
Or an inline class that represents a 2d int coordinate as a long, also not meaningful.
c
Good point about the
private
property use case. I assumed the most common use case would be simple wrapper classes, and that calling
.value
or some unwrapping function would be unnecessary boilerplate.
Now that I think of it, it seems that there are two use cases with different needs: reducing the footprint of stuff like
UInt
and a stronger version of type alias.
a
Personally, I like to use typealias for "Stringly typed" API's for both clarity and ease of changing it in the future.
c
What I don't like about this approach is that typealiases for the same type are fully interchangeable, i.e. you can pass
Name
where
Password
is required and vice versa. I'd like to have automatic unwrapping only
k
Do you want functions on String to work on Name too?
c
Yes
k
But then for exaple the operator "unaryMinus" should also work on UInt.
c
Hmm, let me think about it
I think I was too focused on my particular situation (got a a bunch of strings representing different things; want to gradually migrate to more type-safe solution). In the current form inline classes will serve other cases as well. Thanks for the insights folks!
👍 2