Gav*_*iel 4 static kotlin companion-object kotlin-companion
我希望能够从它的伴随对象访问我的类的 simpleName。
我想要这个:
val o1 = Outer("foo")
val o2 = Outer("bar")
Run Code Online (Sandbox Code Playgroud)
打印以下输出:
Outer: hello
Outer: foo
Outer: bar
Run Code Online (Sandbox Code Playgroud)
实际用例在java中是这样的:
class Outer {
static final String TAG = Outer.class.simpleName();
// and now I'm able to use Outer.TAG or just TAG in both static and non-static methods
}
Run Code Online (Sandbox Code Playgroud)
我尝试了两件事:
将 Outer 的 simpleName 分配给伴生对象的 COMPANION_TAG,然后使用来自伴生初始化和所有 Outer 函数的 COMPANION_TAG。我可以从我需要的任何地方访问 COMPANION_TAG,但不幸的是,我只能通过这种方式获得“Companion”而不是“Outer”。
从伴随对象的初始化访问 Outer.OUTER_TAG。这里的问题是我找不到访问它的方法。
这是代码:
class Outer(str: String) {
private val OUTER_TAG = javaClass.simpleName
companion object {
@JvmStatic val COMPANION_TAG = PullDownAnimationLayout.javaClass.simpleName // gives "Companion" :(
init {
// how can I access OUTER_TAG?
Log.d(OUTER_TAG, "hello") // this gives an error
}
}
init {
Log.d(OUTER_TAG, str) // Outer: ... :)
Log.d(INNER_TAG, str) // Companion: ... :(
}
}
val o1 = Outer()
val o2 = Outer()
Run Code Online (Sandbox Code Playgroud)
为了在 Kotlin 中实现这一点,
class Outer {
static final String TAG = Outer.class.simpleName();
// and now I'm able to use Outer.TAG or just TAG in both static and non-static methods
}
Run Code Online (Sandbox Code Playgroud)
它应该是
class Outer {
companion object {
val Tag = Outer::class.java.simpleName
val Tag2 = Outer.javaClass.simpleName // This will not work
}
}
println(Outer.Tag) // print Outer
println(Outer.Tag2) // print Companion
Run Code Online (Sandbox Code Playgroud)
我想你误解了什么companion是。companion类似于 Java 静态。请参阅此讨论。
| 归档时间: |
|
| 查看次数: |
3214 次 |
| 最近记录: |