Why is `lateinit var` not allowed for inline class...
# announcements
s
Why is
lateinit var
not allowed for inline classes that wrap types that otherwise can be
lateinit
-ed? For example:
Copy code
inline class Id(val value: String)
can’t be used as
Copy code
private lateinit var id: Id
and is there a workaround that is not a nullable field or a data class?
s
I can’t think of a reason this would not be allowed, maybe it’s a bug / future feature. Anyway, you might want to use
typealias
instead for this purpose. If your inline class has other properties/methods, you can replace them with extension methods. So
Copy code
inline class Foo(i: Int) {
  fun bar() = ...
}
Turns into
Copy code
typealias Foo = Int
fun Foo.bar() = ...
It’s not a perfect stand-in, but pretty close. With the typealias solution, you’ll be able to call
bar()
on any Int, which wouldn’t be possible with inline class, but again, pretty close.
s
Thanks, but the typealias has one very significant drawback - comparing them or passing as method parameters would act the same as the aliased class and you won’t get typesafety. For sample:
Copy code
typealias Foo = Int
typealias Bar = Int

foo > bar
// passes, even though they are supposed to be 2 different types
Essentially, typealias doesn’t create a new type
s
Yup, agreed. That’s what I meant by
you'll be able to call bar() on any Int
. If that’s a deal-breaker for you, you might have to settle on a nullable property, or wait till this is fixed 😛 It’s probably worth opening a youtrack ticket for.
107 Views