Hi! I got a custom self-made database library (ja...
# getting-started
m
Hi! I got a custom self-made database library (java) which provides a
SqlServer
object for basically everything needed to interact with our database. In Java, we stored that reference in a static variable, as it was accessed and needed in a lot of different places. As there is no "static" in Kotlin, I'm unsure about how do do it properly.
class Database { val sqlServer = SqlServer(...) }
Does not work, as I can't access it from somewhere else
class Database { companion object { val sqlServer = SqlServer(...) } }
Does not work, as I can't pass any configuration
object Database { val sqlServer = SqlServer(...) }
Does not work, no support for constructors or similar
In Java, we do this:
Copy code
public static void main(String[] args) {
  DbConfig dbCfg = new DbConfig(args);

  Database.init(dbCfg);

  //Database ready to use
  Database.select(...);
}
It would be nice to store the sqlServer object immutable and as a nonnull value. Maybe i'm just dumb rn, it's sort of my first kotlin project. 🙂 Thanks!
d
moehritz: Where is the
sqlServer
object in your Java code?
m
@diesieben07
private static SqlServer sqlServer
it is assigned in
public static void init(...)
, and used by the other methods/made public by a getter
d
Well, apart from the fact that that is terrible OOP design... You need a
var
in Kotlin as well then.
m
Any suggestions then? It's just impractical not to do it that way, every module of our software accesses this database, and there is always just one
d
I suggest you take a look at dependency injection. It makes your code a lot more flexible, modular and testable.
m
I'll take a look, thank you! For now, I settled with initializing it in the main method, storing it there and relying on the fact that Objects are initialized lazily
t
though better to use dependency injection
n
I would make this an
object Database(val dbCfg: DBConfig) {...}
m
Constructors are not allowed for objects, so this won't compile @nkiesel
n
true. So instead a
open class Database(dbConfig: DBConfig) { ... }; object DB : Database(myConfig) { ... }
?