hello, I've an issue with parameters visibility an...
# announcements
r
hello, I've an issue with parameters visibility and constructors. I google the problem but I wasn't able to find any solution, so given the following code:
Copy code
class MyAwesomeView: FrameLayout {
	constructor(context: Context?, attrs: AttributeSet? = null) : super(context, attrs)
	constructor(context: Context?, attrs: AttributeSet?, parm1: Int) : super(context, attrs, parm1)
	constructor(context: Context?, attrs: AttributeSet?, parm1: Int, parm2: Int) : super(context, attrs, parm1, parm2)
	
	init {
		context.someMethod(attrs)
	}
}
The init method cannot access attrs, I'm getting "Unresolved reference 'attrs'". Why is that? how can I make init access attrs. Shouldn't be enough by adding attrs to constructors as it is here?
n
So far as I know,
init
is called after the constructor, not as the constructor body. Try making
attrs
a val
d
init
is called after primary constructor
secondary constructors are called after init
n
TIL. That’s pretty confusing though
d
Yeah, this is why secondary constructors were not available in Kotlin for long time
r
Read your comment and documentation and I'm still not sure how to solve the problem 🙂. Would you call context.someMethod(attrs) on secondary constructors body then? That works, but I'm not quite sure if it's the best
s
Create a private method
private fun init(...)
and just call it from the body of all your secondary constructors.
g
Copy code
class MyAwesomeView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
    : FrameLayout(context, attrs, defStyleAttr) {

    init {
        attrs...
    }
👌 3