Expect-actual using typealias

What is the correct way to define this multiplatform common type?

common:

expect class YearMonth: Comparable<YearMonth> {
    val year: Int // How should I declare this property?
}

jvm:

// This typealias is a requirement:
actual typealias YearMonth = java.time.YearMonth

The above jvm declaration causes a compile error: The following declaration is incompatible because visibility is different: private final val year: Int defined in java.time.YearMonth

3 Likes

I have also tried this:

common:

expect class YearMonth: Comparable<YearMonth>

expect val YearMonth.year: Int

jvm:

actual typealias YearMonth = java.time.YearMonth

actual val YearMonth.year: Int get() = year

This compiles and seems to work but

  • less elegant
  • a warning is raised on the property’s jvm implementation: This property conflicts with synthetic extension and should be removed or renamed to avoid breaking code by future changes in the compiler
1 Like

I would go with your extension method approach. The issue is that multiplatform and Java interop don’t work 100% together (you can’t set an expect upon requiring a Java class). Alternatively you can always use the getter syntax with an expect fun getYear():Int instead (as that is what the Java implementation actually does). Possibly then creating a common extension property that calls it to make the API nicer.

2 Likes