如果我希望像Kotlin中的静态函数一样使用语法,哪种方法更好? [英] Which way is better if I hope to use a syntax just like static function in Kotlin?
本文介绍了如果我希望像Kotlin中的静态函数一样使用语法,哪种方法更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道Kotlin中没有静态函数,所以我在myClass1.kt和myClass2.kt中编写了两个代码
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!
主要
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();
}
}
推荐答案
让我们反编译kotlin字节码并查看Java代码.
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.
这篇关于如果我希望像Kotlin中的静态函数一样使用语法,哪种方法更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文