tl:dr; Is it possible to import
a method inside a companion object of another class, without qualifying the import with Companion
? That is, is there any possible way I can say import Bar.toFoo
instead of import Bar.Companion.toFoo
, assuming toFoo
is a method on Bar
's companion object?
We're migrating a class from Java to Kotlin. Our class looks like this:
class Bar {
static Foo toFoo() {
return new Foo();
}
}
And then, to use it, from a class that happens to be Kotlin, we say something like:
import Bar.toFoo;
// ...
Bar().convert(toFoo()); // like a Java 8 Collector
// ...
When we convert Bar
to Kotlin, it looks like this:
class Bar {
companion object {
@JvmStatic fun toFoo() = Foo()
}
}
We'd like the calling code to work without modification, however
import Bar.toFoo
no longer works, even with @JvmStatic! Instead, we have to update it to
import Bar.Companion.toFoo
which we'd rather not have to do -- we want to switch the Bar class to Kotlin without updating the callers.
Thoughts? We're using Kotlin 1.1.2-2.
Bar().convert(toFoo())
instead ofBar().toFoo()
. Why does it have to be static?toFoo()
actually is a Java 8 Collector class, likeCollectors.toList()
orCollectors.toSet()
, and is modeled the same way.import static example.Bar.toFoo;
should work (changed package from your example because Java cannot have classes in the root package) - what compiler error are you seeing? And is it in the IDE or in the build?import static
statement. The error I'm seeing isunresolved reference
.It is a compile time error to import a type from the unnamed package.
But it sounds like I misunderstood the question anyway, because it sounds like you are trying to import the companion object function into another Kotlin class.