I have a Quantity/Units library in Kotlin which has classes like Weight
, Distance
, Force
. These classes inherit from a Quantity
class and each contain a nested enum class Unit
with information about the respective units for each type of quantity.
As a kind of physical oddity, the consumption of an electric car (e.g. kWh/100km) is technically the same dimension as a force, so the Force.Unit
class contains both NEWTON
and KILOWATTHOUR_PER_100_KILOMETERS
.
Of course, we use FuelConsumption
for combustion cars and the quantity for electric cars should look similar, so I have created a typealias ElectricConsumption = Force
.
For some reason, I can't access the inner class ElectricConsumption.Unit
through that typealias. This is extremely inconvenient. Is this by design? Why? Is there a workaround?
class A {
enum class B { X }
}
typealias AA = A
fun main() {
print(A.B.X) // prints X
print(AA.B.X) // Unresolved reference: B
}
CodePudding user response:
Given that the Kotlin Language Specification says "Type alias introduces an alternative name for the specified type", you would reasonably expect to be able to use the typealias name wherever you can use the original type name. This is not the case in your example, and I suspect that this is a bug (KT-34281) as it obviously doesn't conform to the official description of typealias.
You might be able to work around this issue by using import as
instead of typealias:
import A as AA
class A {
enum class B { X }
}
fun main() {
print(A.B.X)
print(AA.B.X)
}
See it working at https://pl.kotl.in/1JUSVZtCL