Kotlin Java-oriented interop: Idiomatic type for lazy collection?

When using targeting for Java interaction, what type should be used for a lazy collection?

  • Sequence<T> is most important for callers in Kotlin due to the fact that the extension functions on it are lazy by default, but force Java subscribers of the stdlib type Kotlin to convert the sequence iterator manually (the sequence does not extend iterability!)
  • Iterable<T> makes sense for Java callers due to implicit use in loops, but calls up suspicious Kotlin calls to accidentally fall for laziness to nonsense extension functions
  • Stream<T> is optimal for both Java and Kotlin subscribers, but may have overhead and is Java 8+ (Kotlin 6+ targets)
+7
lazy-evaluation kotlin kotlin-interop
source share
1 answer

You can make everyone happy by completing all three. eg:.

 data class User(val name: String) fun userSequence(): Sequence<User> = TODO() fun usersLazily(): Iterable<User> = userSequence().asIterable() fun userStream(): Stream<User> = userSequence().asStream() 

By not using a simple name, such as users for any of these functions, you make the caller a little redundant for what they really want:

  • Kotlin users will use userSequence .
  • Java 1.6 and 1.7 users will use usersLazily .
  • Java 1.8 users will use userStream .

userStream must be defined in a separate JAR adding JDK 1.8 support for your 1.6 / 1.7 JAR (similar to how org.jetbrains.kotlin:kotlin-stdlib-jre8 does for org.jetbrains.kotlin:kotlin-stdlib ).

With that said, I would question if you really need to support Java 1.6 or 1.7 support. If you do not notice that you do not, you can put userSequence and userStream in the same JAR and not even define usersLazily .

+2
source share

All Articles