Dave Ford
Dave Ford

Reputation: 1974

Load resource from local directory with no class

I frequently use code like this:

val sql = getResource(this.javaClass, "foo.sql")

or this:

val sql = getResource(::MyClass.javaClass, "foo.sql")

But with Kotlin, I find myself using top-level functions quite often where there is no object or class.

How would I do such a thing with a top-level function?

Upvotes: 3

Views: 1178

Answers (1)

mfulton26
mfulton26

Reputation: 31224

The JDK does not define a static getResource method so I am not certain what library you are using to load resources this way but I suspect it is Guava. If not, I recommend using it as it has two getResource methods: one that takes a class as an argument and one that uses the context class loader. Using the latter you can do the following:

import com.google.common.io.Resources.getResource

val sql = getResource("foo.sql")

Upvotes: 1

Related Questions