hi, what are reasons to have companion object in c...
# announcements
r
hi, what are reasons to have companion object in class and not a static block(methods, variables) instead?
l
You don’t need to have anything in class and that way it’ll become
static
. The thing with companion object is that it supports inheritance and so on, which makes it more powerful.
r
do you have an example when do you need inheritance for companion object?
You don’t need to have anything in class and that way it’ll become
static
but I want to have same namespace as class
d
Actually you need to annotate companion object methods with
@JvmStatic
if you want them to be truly static. Otherwise you will need to access them via
Clazz.Companion.foo()
instead of
Clazz.foo()
when calling from java.
It only matters for interpolability.
l
Namespacing with companion object or top level objects is not advised https://github.com/yole/kotlin-style-guide/issues/6
r
@dragas In our application we annonate all methods in comapnion object with
@JvmStatic
because we do not have any benefits from companion object
@lupajz for example we have class Array, and we want to have MAX_SIZE of Array, in java i make a static variable in Array class, so will be Array.MAX_SIZE, in Kotlin we should have a val ARRAY_MAX_SIZE in same package?
what about autocomplete then?
l
Yes I would do as you are saying
const val ARRAY_MAX_SIZE = xx
probably have it
private
. Autocomplete is mentioned in next comments on github
r
but if for some reason we want to change Array class name to something else, then refector will not apply to those constants 😞
l
Well you still should have it in your class file, so you can refactor it in more step. But it’s up to you how do you want to handle this situation. I try to follow language not how one would do it in Java
r
more steps mean you can forget, and then you have inconsistent names in project
l
nah I always try to look at classes I refactored and since I put such constants above class I can’t miss them.