Hi, can someone explain why IntelliJ is giving an ...
# android
m
Hi, can someone explain why IntelliJ is giving an error like that? IntelliJ is saying that
Variable mOnClickListener must be initialized
and underlines the
mOnClickListener
inside the
init
statement. I have been doing the same thing in Java and it didn’t say anything like that. Am I missing something here ? EDIT : I am trying to make a custom layout here. I have been doing this in Java all the time - assigned
OnClickListener
to a private variable and then setting it to a button in the constructor.
Copy code
class CustomLayout(context: Context) : FrameLayout(context) {

    companion object {
        const val RESOURCE = R.layout.layout_custom
    }

    init {
        LayoutInflater.from(context).inflate(RESOURCE, this)
        // IntelliJ underlined `mOnClickListener` here and it says : "Variable mOnClickListener must be initialized"
        btnSend.setOnClickListener(mOnClickListener) 
    }

    private val mOnClickListener = OnClickListener { context.toastInfo("Info") }
}
Java version of the code which works fine
Copy code
public class CustomLayout extends FrameLayout{

     public CustomLayout(){
          // inflating the xml layout
          ...
          btnSend.setOnClickListener(mOnClickListener);
     } 

     private OnClickListener mOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            // do something
        }
    };  

}
a
Kotlin runs init blocks and property initializer expressions in order from top to bottom in the class. Move the listener to be above the init block.
And drop the
m
🙂
m
😮interesting… thank you pal for the quick reply. dropping
m
is gonna be the hardest one for me 😄
😄 1
a
If it helps, remember that kotlin has no such thing as raw fields, all properties are backed by real get/set methods (and occasionally they're optimized out). You wouldn't put
m
in a getter/setter, so you don't need them here
🙂 1
m
Hmm, I see it now. Got it. Got bored in the quarantine and yesterday decided to try some Kotlin. So far loving it. 😍 [secretly copying your message to my secret Kotlin notes]
👍 1