Benjamin
Benjamin

Reputation: 7368

Cannot access expected class constructor parameters in kotlin multi-platform

I'm currently working on a multi-platform module using kotlin. To do so, I rely on the expect/actual mechanism.

I declare a simple class in Common.kt:

expect class Bar constructor(
    name: String
)

I'd like to use the defined class in a common method (also present in Common.kt):

fun hello(bar: Bar) {
    print("Hello, my name is ${bar.name}")
}

The actual implementation is defined in Jvm.kt:

actual data class Bar actual constructor(
    val name: String    
)

The problem is I got the following error inside my hello function

Unresolved reference: name

What am I doing wrong?

Upvotes: 9

Views: 4974

Answers (2)

Braian Coronel
Braian Coronel

Reputation: 22867

Expected classes constructor cannot have a property parameter

Therefore it is necessary to describe the property as a class member with val name: String

Actual constructor of 'Bar' has no corresponding expected declaration

However, for the actual constructor to match the expected declaration the number of parameters has to be the same. That is why the parameter is also added name: String in the constructor in addition to the existence of the property.

expect class Bar(name: String) {
    val name: String
}

actual class Bar actual constructor(actual val name: String)

Note: If we leave the constructor empty of the expected class we see how the IDE complains when adding a constructor in the current class for the incompatibility.

GL

Upvotes: 5

Alexey Romanov
Alexey Romanov

Reputation: 170735

It should be val name in the expect part as well, either in the constructor parameter list or as a member property.

Upvotes: 1

Related Questions