Hi ! Is there any way to force Tree Shaking in Kot...
# getting-started
a
Hi ! Is there any way to force Tree Shaking in Kotlin/JVM ? I have this really simple code
Copy code
private inline fun execute(block: () -> Unit) = block()

fun main() {
	execute { println("test") }
}
But when I see the Bytecode, it creates an
execute
static method on the MainKt class but never use it, is there a way to say to the compiler to not generate this method and just inline ?
e
ProGuard or r8 can
a
Does any of these works for PC ? For both it saids that it's optimizers for Android Apps, I'm not doing an Android app but a Game on PC
e
yes, both work for JVM. I have an example at https://github.com/ephemient/utf-8b
a
And it's only possible with a third party library, not with the Kotlin or JVM compiler ?
e
@jw has a writeup about using r8 for this purpose: https://jakewharton.com/shrinking-a-kotlin-binary/
this is not a feature of Kotlin or Java SDK itself, no.
in most cases it simply isn't something to worry about - JVM doesn't JIT-compile unused methods so the only cost is some extra storage
a
Yes but I just want to optimize my jar so it's lighter
And it's also for testing new tools and learning this because it could be useful for me in future jobs
I have a werid error and I can't find any help online, do you know why I'm getting this ?
Error: Missing class android.annotation.SuppressLint (referenced from: kotlinx.coroutines.debug.AgentPremain)
e
maybe take out
kotlinx-coroutines-debug
from your production dependencies, otherwise you'll have to fill in some implementation for that annotation class to satisfy r8
a
But I only have this dependency
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.0")
e
then check your dependency graph, you may be pulling in
kotlinx-coroutines-test
or
-debug
from somewhere
h
Hm, why does
crossinline
do not work?
Copy code
private inline fun execute(crossinline block: () -> Unit) = block()

fun main() {
	execute { println("test") }
}
e
crossinline has no effect here because its purpose is completely unrelated. Kotlin generates a non-inline function for the purposes of reflection.
h
Ah, thanks!
y
Basically yes compilers in general try not to optimize as much for the purposes of bing able to use reflection and testing later on. Minifiers are then used to remove dead bytecodes
j
ProGuard also works for non-Android apps (it actually started out as a Java optimizer/shrinker 20 years ago, before Android) https://www.guardsquare.com/manual/setup/gradle