https://kotlinlang.org logo
#announcements
Title
# announcements
s

spand

10/07/2019, 6:29 AM
Is it possible to have an
operator val invoke
property ? The error message seems to suggest its possible but I cant find a way
Modifier 'operator' is not applicable to 'member property without backing field or delegate'
Copy code
class Foo {
    companion object {
        operator val invoke = {}
    }
}
s

Sebastian Sellmair [JB]

10/07/2019, 6:29 AM
No, How would you access it?
What do you want to do with this and why is operator fun invoke not an option? 🤔
s

spand

10/07/2019, 6:36 AM
I feel this is a bit repetetive:
Copy code
interface Foo {
    var prop1: String
    var prop2: String
    
    companion object {
        operator fun invoke(prop1: String, prop2: String) = object : Foo {
            override var prop1 = prop1
            override var prop2 = prop2
        }
    }
}
So maybe this would be a shorter way to express the same:
Copy code
interface Foo2 {
    var prop1: String
    var prop2: String

    class Helper(override var prop1: String, override var prop2: String) : Foo2
    
    companion object {
        operator fun val invoke = ::Helper::invoke
    }
}
k

kralli

10/07/2019, 6:48 AM
Copy code
interface Foo2 {
    var prop1: String
    var prop2: String

    class Helper(override var prop1: String, override var prop2: String) : Foo2

    companion object {
        operator fun invoke(prop1: String, prop2: String) = Helper(prop1, prop2)
    }
}
s

spand

10/07/2019, 6:51 AM
Still four counts of
prop1
k

kralli

10/07/2019, 7:01 AM
Well, you can’t define a function without it’s parameters, but the
invoke
operator function is the only way to call
Foo2
directly.
s

spand

10/07/2019, 7:11 AM
Yeah I thought so too. Except the error message sort of hinted of the possibility of a an
operator val
.
r

Ruckus

10/07/2019, 2:40 PM
No, it isn't. It knows that
operator
can't be used there, and to make a nice message, it generates a string representation of your use, which in this case happens to be on a "member property without backing field or delegate".