# codingconventions


03/15/2023, 9:48 PM
regarding a large codebase needing good java interop, thoughts on the function signature
Copy code
class ConvertedOldModelObject private constructor(oldCtorArg: OldJavaDomainType, ...) {
  companion object {
    @JvmStatic @JvmName("create") operator fun invoke(oldCtorArg: OldJavaDomainType, ...) {
      //some caching logic to try to avoid hanging on to allocaitons, a kind of poor mans constant pool

      return CovertedOldModelObject(oldCtorArg, cachedArgs, ...)
pros: • I get
OldJavaDomainType oldThing = OldJavaDomainType.create(args...)
from java • I get
val x = OldJavaDomainType(args...)
from kotlin cons: •
companion object operator fun invoke
seems like a kind of nifty hack, not sure how somebody else would feel stumbling across it • reasonable alternatives like simply offering a global function for kotlin and a simpler
fun create()
method for java seems sufficient, though slightly bloatier


03/15/2023, 10:16 PM
pooling is generally a bad idea in modern JVMs (and even Android ART)
any sort of thread safety will be slower than simply getting new objects from the bump allocator and letting GC clean them up
as for the API itself, the
companion object { operator invoke() }
trick is fine. overall I think it's more common in Kotlin to use
Copy code
interface Foo
private class FooImpl(...) : Foo
public fun Foo(...): Foo = FooImpl(...)
but that doesn't lead to the same Java API

Youssef Shoaib [MOD]

03/16/2023, 10:12 AM
companion object operator fun invoke
is definitely idiomatic Kotlin, but yes sometimes people just have a top-level function with the class name. Personally, I think here it makes the most sense to use a companion object so that you get the wanted experience from Java