7

Actually the question is, which approach is better and which convention do you use?

E.g. in order to improve readability we've added this field in Java class:

class Game {

    private static final int MAX_PLAYERS = 10;

    public boolean canWePlay(int playersCount) {
         return playersCount <= MAX_PLAYERS;
    } 

    // getters and setters
}

Now the better approach is to use companion object:

class Game {

    fun canWePlay(playersCount: Int): Boolean {
        return playersCount < MAX_PLAYERS
    }

    companion object {

        val MAX_PLAYERS = 10
    }
}

or and const val outside the class:

private const val MAX_PLAYERS = 10

class Game {

    fun canWePlay(playersCount: Int): Boolean {
        return playersCount < MAX_PLAYERS
    }
}

or maybe do you use different approaches?

And the additional question is, if we use the second convention, should we use camel case or uppercase with underscore? (I'm talking manly about Android code).

Nominalista
  • 4,632
  • 11
  • 43
  • 102
  • 4
    @Rahul: actually this is not a duplicate. He is asking how to declare a private static final and the linked question just tells how to declare a static final. – jonathanrz Aug 05 '17 at 12:21
  • @jonathanrz exactly... – Nominalista Aug 05 '17 at 12:48
  • answering your question, IMO the better way is the const one. I don´t know any way to define a companion object as private. – jonathanrz Aug 05 '17 at 12:59
  • @jonathanrz What naming convention do you use? – Nominalista Aug 05 '17 at 13:43
  • since I converted a codebase from Java, I kept the convention from java (uppercased), but I don´t know if the Kotlin community has changed the convention. – jonathanrz Aug 05 '17 at 13:47
  • I think the second approach is better if you have multiple classes declared within one file. Also check out [this](https://stackoverflow.com/questions/38381748/why-do-we-use-companion-object-as-a-kind-of-replacement-for-java-static-fields) for further explanation of using `companion object`. – BakaWaii Aug 05 '17 at 19:26
  • Is it possible to overturn the duplicate mark and re-open this question...? – Julius Sep 12 '18 at 17:35
  • Yes, this one is about "private" static final. Anyone know the answer? – Todd W Crone Jan 31 '19 at 20:41

0 Answers0