s

    Sebastien Leclerc Lavallee

    2 years ago
    I’m having a hard time with
    companion
    and
    object
    usage inside my Swift code. Let say we have this Kotlin 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:
    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

    2 years ago
    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

    2 years ago
    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

    2 years ago
    try
    SomeClass.Companion().toSomeString
    s

    Sebastien Leclerc Lavallee

    2 years ago
    Yep! That seems to work. Strange I have to instanciate my companion each time. 🤷‍♂️ Thanks!
    saket

    saket

    2 years ago
    You’ll always get the same instance of the companion
    s

    Sebastien Leclerc Lavallee

    2 years ago
    Thanks! Makes sense 🙂