Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 479
Benjamin Avatar asked May 06 '19 12:05

Benjamin


1 Answers

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

like image 67
Braian Coronel Avatar answered Oct 31 '22 15:10

Braian Coronel