android - Kotlin 构造函数属性 val 不能在类中使用

标签 android kotlin constructor

后续作品

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-only val.

关于android - Kotlin 构造函数属性 val 不能在类中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53119757/

相关文章:

java - 两个线程可以同时使用同一个套接字吗?这可能会出现问题吗?

android - resources.ap_ 在编译我的 android 项目时不生成

android - Kotlin 和 Android Espresso 测试 : Adding extension function with receiver

java - 如何重写构造函数

c++ - 将对象传递给函数不会导致构造函数调用

c++ - 模板忽略了常量(为什么?)

android - 将 mimetype 'application/octet-stream' 与 SAF 选择器一起使用适用于本地文件,但不适用于 Google Drive 中的相同文件

javascript - 可以在 Android 和 iOS 设备上通过 Javascript 进行 TCP 或 WebSockets 调用吗?

android - 从Firestore中删除文档后,如何实时更新Recyclerview?

java - 像谷歌助手一样通过语音命令启动 Android 应用程序