Following works
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
}
and this doesn't (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
}
I am new to Kotlin and just confused why can't you use the val properties in the class itself. Can someone please explain? Thanks
The block of code surrounded by parentheses is the primary constructor: (val firstName: String, var age: Int) . The constructor declared two properties: firstName (read-only property as it's declared using keyword val ) and age (read-write property as it is declared with keyword var ).
A Kotlin class can have a primary constructor and one or more additional secondary constructors.
The second doesn't work as you are not declaring any properties for the class. Just mentioning them in the brackets does not make them properties, rather it can be compared as if they were just parameters of a constructor.
You either want to use var
or val
... you can make them private
if you like.
Check also 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
.
tabCount
and fm
in class PagerAdapter(tabCount: Int, fm: FragmentManager?)
are just constructor parameters.
They are not members of the class.
It is like
class PagerAdapter extends FragmentStatePagerAdapter {
PagerAdapter(int tabCount, FragmentManager fm) {
super(fm)
}
...
}
in Java.
You have to specify they are class fields by adding val
in front of them.
class PagerAdapter(val tabCount: Int, val 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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With