Kotlin issue, You should face
My team application is based on Kotlin. (over 90%). Most of function and code work well. But Sometimes we should face unpredicted issue.
Kotlin with Java
I know still you might be with Java. If you want to use Kotlin on your project. Biggest problem is Nullable argument between Java to Kotlin.
// Kotlin
fun callee(text: String) {
// doSomething
}// Java
public void caller() {
String text = makeText(); // can return nullable
callee(text);
}
In this case, There is potential IllegalArgumentException. When kotlin function with non-null arguments is called from other, Kotlin checks if argument is null.
All Android guys know Google supports @Nullable and @NonNull
Even though sometimes we forget those annotations.
If someone of your team members, even you, might forget it, Application can occur error.
My Solution
Fully convert to Kotlin
or
Use nullable to all arguments for Java (add "?")
When Dagger meets Databinding
Sometimes this code occurs compilation error :
class HomeActivity : Activity {
private lateinit var binding : ActHomeDatabinding
@Inject val model : HomeModel
}
After generating code, Compiler show error ActHomeDatabinding cannot find...
while compilation.
By Jetbrains, It’s related to lateinit
. Compiler check type of lateinit
var. But sometimes compiler fail to find type.
My solution
It’s actually my colleagues solution. Just simply to avoid type-check, create wrapping
// example
class BindingWrapper<out T> constructor(val binding:T)class BindingFragment() :Fragment {
lateinit val wrapper : BindingWrapper<FragmentLayoutBinding>
val binding : FragmentLayoutBinding
get() = wrapper.binding
}
Jetbrains suggestion
class BindingFragment() : Fragment {
@JvmField var binding : FragmentLayoutBinding? = null
}
Inline function, Lambda and Proguard
I cannot specify the case. If you write 3 depth inline or SAM function, you may face error while obfuscation of proguard. Especially, let
run
apply
also
My solution
Unwrap inline
// before
data?.let {
doSomething(it) {
doSomething2(it)
}
}// after
val actualData = data ?: return
doSomething(actualData) {
doSomething2(it)
}
}
Kotlin is so easy to learn and joyful. Java 6 has limitations to do modern style. For Android, Kotlin is good replacement language. But be aware that there is new curves for new tools.
Happy code with Kotlin.