I know there isn't a static function in Kotlin, so I write two code in myClass1.kt and myClass2.kt
I don't know which is better, could you tell me? Thanks!
Main
class HomeActivity : DemoActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Display1(this)
Utility.Display2(this)
}
}
myClass1.kt
import android.content.Context
import android.widget.Toast
fun Display1(mContext: Context){
Toast.makeText(mContext, "Hello, World 1", Toast.LENGTH_LONG).show();
}
myClass2.kt
import android.content.Context
import android.widget.Toast
object Utility {
fun Display2(mContext: Context) {
Toast.makeText(mContext, "Hello, World 2", Toast.LENGTH_LONG).show();
}
}
Let us decompile the kotlin bytecode and see the java code.
myClass1.kt
public final class MyClass1Kt {
public static final void Display1(@NotNull Context mContext) {
Intrinsics.checkParameterIsNotNull(mContext, "mContext");
Toast.makeText(mContext, (CharSequence)"Hello, World 1", 1).show();
}
myClass2.kt
public final class Utility {
public static final Utility INSTANCE;
public final void Display2(@NotNull Context mContext) {
Intrinsics.checkParameterIsNotNull(mContext, "mContext");
Toast.makeText(mContext, (CharSequence)"Hello, World 2", 1).show();
}
private Utility() {
INSTANCE = (Utility)this;
}
static {
new Utility();
}
}
The second way is clearly not what you intended. There is an unneeded instance creation.
Definitely not the second way. The first way is fine if the method is a specific use case for the object.
However, in your example, you probably want to invoke the method when context is available. Then, I would recommend using extension instead.
fun Context.display1(){
// In the function, `this` is refer to the context
Toast.makeText(mContext, "Hello, World 1", Toast.LENGTH_LONG).show();
}
Then, in Activity
, you can write like
fun example() {
display1()
}
instead of
fun example() {
Display1(this)
}
Actually either one is good. Use case will depend mostly on methods visibility. You have more visibility control in second case because it is not restricted by package (like the first one). First case I believe would force you to place your .kt file in highest package hierarchie in order to be used everywhere in your code.