Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to have a private file constant in Kotlin

Tags:

kotlin

Suppose I have some Utils.kt file which will contain only some utility functions, no classes, no objects. And suppose that those functions use some common set of constant values.

So I do something like this:

package myapp

private val CONST1 = 1
private val CONST2 = 2

public fun function1() {}
public fun function2() {}

Unfortunately Kotlin treats private as "available to the whole package". So CONST1 and CONST2 are available to all files which are in the same package. The only way to isolate them is to move this file to a separate package.

But what if I have several utility files like this, each with its own set of private constants. Then i have only two options: move each of them to a unique package or give up and have consts from all of them accessible everywhere.

Either way seems to create clutter.

Any options or advice?

(upd: actually, I must say this is one of those rare things that bother me in Kotlin - no way to make some entity be file-local (without using some syntax hacks): it's either available to whole package or to everyone at all)

UPD: This question is now obsolete (see the accepted answer)

like image 873
dimsuz Avatar asked Apr 18 '15 12:04

dimsuz


People also ask

How do I create a constant file in Kotlin?

Android App Development for Beginners In Kotlin too, we have a keyword to create such a variable whose value will remain as constant throughout the program. In order to declare a value as constant, we can use the "const" keyword at the beginning.

Where should I keep my constants in Kotlin?

You don't need a class, an object or a companion object for declaring constants in Kotlin. You can just declare a file holding all the constants (for example Constants. kt or you can also put them inside any existing Kotlin file) and directly declare the constants inside the file.

How do you define a String constant in Kotlin?

To define a String constant in Kotlin, use constant and val keyword for the String. The following is a simple code snippet to define a String as constant which can be accessed using the name GREETING . const val GREETING = "Hello World!"


1 Answers

Top-level declarations with private visibility are visible only in the file where they are declared.

(original answer, valid when the question was asked: Kotlin does not have any concept of file-local scope, and to the best of my knowledge there are no plans to introduce it. If you don't like package scope (why?), you can create an object encapsulating the functions and the private constants that they use.

like image 109
yole Avatar answered Sep 18 '22 15:09

yole