Kotlin Suspend Interface reversal
English | 中文
Generate platform-compatible extension types for interfaces or abstract classes that contain suspend functions, based on KSP.
Summary
Suppose: You have an interface like the following:
interface Foo {
suspend fun value(): Int
val name: String
}
Now, you want this interface to be implemented by your users, but it's not directly available to Java users!
At this point, you provide two additional interfaces to accommodate blocking and asynchrony, as follows:
In this way, Java users can implement it:
public class FooImpl implements JBlockingFoo {
@Override
public int valueBlocking() {
return 1;
}
@Override
public String getName() {
return ;
}
}
Usage
JVM
plugins {
id("org.jetbrains.kotlin.jvm") version "$KOTLIN_VERSION"
id("com.google.devtools.ksp") version "$KSP_VERSION"
}
repositories {
mavenCentral()
}
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$COROUTINES_VERSION")
compileOnly("love.forte.suspend-interface-reversal:annotations:$VERSION")
ksp("love.forte.suspend-interface-reversal:processor:")
}
Multiplatform
[!note]
Support JVM and JS.
Code
Add @SuspendReversal to the interfaces or abstract classes.
@SuspendReversal
interface Foo {
val age: Int () =
:
name: String
}
[!note]
If SuspendReversal.markJvmSynthetic = true,
then @JvmSynthetic must (or is strongly recommended) be added to the suspend function.
Cautions
-
The processor will only handle the abstract suspend function.
-
In Java, functions with a return value of are treated as (for async)
e.g.
interface Foo {
suspend fun
{ }
}
: {
{
runBlocking()
}
}
[!warning]
The judgment is very rough and not very reliable.
For example, it won't determine if it's final or not, if the parameters are inherited or not, and so on.
Useful Links
Kotlin suspend transform compiler plugin
: Kotlin compiler plugin for converting suspend functions to platform-compatible functions.
License
see LICENSE .
Copyright (c) 2024 ForteScarlet
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.