Is it possible to have an `operator val invoke` pr...
# announcements
s
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
No, How would you access it?
What do you want to do with this and why is operator fun invoke not an option? 🤔
s
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
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
Still four counts of
prop1
k
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
Yeah I thought so too. Except the error message sort of hinted of the possibility of a an
operator val
.
r
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".