groostav
03/15/2023, 9:48 PMclass 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 bloatierephemient
03/15/2023, 10:16 PMephemient
03/15/2023, 10:18 PMephemient
03/15/2023, 10:26 PMcompanion object { operator invoke() }
trick is fine. overall I think it's more common in Kotlin to use
interface Foo
private class FooImpl(...) : Foo
public fun Foo(...): Foo = FooImpl(...)
but that doesn't lead to the same Java APIYoussef Shoaib [MOD]
03/16/2023, 10:12 AMcompanion 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