https://kotlinlang.org logo
s

Sebastien Leclerc Lavallee

05/06/2020, 8:55 PM
I’m having a hard time with
companion
and
object
usage inside my Swift code. Let say we have this Kotlin code:
Copy code
class SomeClass {
    companion object {
        fun someIntFunction(): Int {
            return 1
        }
    }
}

fun SomeClass.someBoolFunction(): Boolean {
    return false
}

fun SomeClass.Companion.toSomeString(): String {
    return "to Some String"
}

object SomeOtherStatic {
    fun stringStuff(): String {
        return "String Stuff"
    }
}
And with that Swift code:
Copy code
let some = SomeClass()
let someBool = some.someBoolFunction()
let someInt = SomeClass.Companion.someIntFunction()
let someString = SomeClass.Companion.toSomeString()

let otherString = SomeOtherStatic.stringStuff()
I get errors from inside Xcode:
Instance member 'someIntFunction' cannot be used on type 'SomeClass.Companion'; did you mean to use a value of this type instead?
I have this error for
someIntFunction
,
toSomeString
and
stringStuff
. The compile thinks they are instance functions 🤔 Is there something I am doing wrong? Thanks!
c

Casey Brooks

05/06/2020, 9:01 PM
Yes,
companion
and
object
singletons must be accessed through a factory method when called in Swift https://kotlinlang.org/docs/reference/native/objc_interop.html#kotlin-singletons
s

Sebastien Leclerc Lavallee

05/06/2020, 9:14 PM
As far as I know, those aren’t singleton members. Maybe I’m wrong. And I don’t see any singleton property in my Swift code. And the mapping table has different for ``companion` member` and
Singleton
b

basher

05/06/2020, 10:02 PM
try
SomeClass.Companion().toSomeString
s

Sebastien Leclerc Lavallee

05/06/2020, 10:40 PM
Yep! That seems to work. Strange I have to instanciate my companion each time. 🤷‍♂️ Thanks!
s

saket

05/07/2020, 12:16 AM
You’ll always get the same instance of the companion
❤️ 2
s

Sebastien Leclerc Lavallee

05/07/2020, 12:22 AM
Thanks! Makes sense 🙂
6 Views