后续作品
class PagerAdapter(var tabCount: Int, fm: FragmentManager?) : FragmentStatePagerAdapter(fm) {
override fun getItem(p0: Int): Fragment {
return when (p0) {
0 -> TabFragment1()
1 -> TabFragment2()
2 -> TabFragment3()
else -> throw IllegalArgumentException("Invalid color param value")
}
}
override fun getCount() = tabCount
}
这不是( Unresolved reference :tabCount)
class PagerAdapter(tabCount: Int, fm: FragmentManager?) : FragmentStatePagerAdapter(fm) {
override fun getItem(p0: Int): Fragment {
return when (p0) {
0 -> TabFragment1()
1 -> TabFragment2()
2 -> TabFragment3()
else -> throw IllegalArgumentException("Invalid color param value")
}
}
override fun getCount() = tabCount
}
我是 Kotlin 的新手,只是很困惑为什么不能在类本身中使用 val 属性。有人可以解释一下吗?谢谢
最佳答案
第二个不起作用,因为您没有为该类声明任何属性。 只是在括号中提及它们并不能使它们成为属性,而是可以将它们进行比较,就好像它们只是构造函数的参数一样。
你要么想使用var
,要么使用val
...如果你愿意,你可以将它们设为private
。
同时检查 Kotlins reference about classes and inheritance, more specifically the constructor chapter :
In fact, for declaring properties and initializing them from the primary constructor, Kotlin has a concise syntax:
class Person(val firstName: String, val lastName: String, var age: Int) { ... }
Much the same way as regular properties, the properties declared in the primary constructor can be mutable
var
or read-onlyval
.
关于android - Kotlin 构造函数属性 val 不能在类中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53119757/