-1

What I want is to do this (which is in Java):

public class MainActivity exteds AppCompatActivity{
    ImageView logo;

    @override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        logo = findViewById(R.id.logo);
    }

when taking it to Kotlin I get an error:

enter image description here

Please could you tell me which of the options to keep so that the error does not appear?

enter image description here

and what class is TODO()?

pradeexsu
  • 1,029
  • 1
  • 10
  • 27
Pxnditx YR
  • 79
  • 1
  • 10

4 Answers4

3

Use lateinit which will allow you to initialize the property later on.

lateinit var logo: ImageView

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    logo = findViewById(R.id.logo)
}
Ali Ahsan
  • 985
  • 11
  • 16
1

You can initialize as null and later use it

var logo: ImageView? = null
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.simple_layout)
        logo = findViewById(R.id.imageView)
    }
ruben
  • 1,745
  • 5
  • 25
  • 47
1

You can't reassign a val, so I would suggest you make it a var. Since you also want to initialize it later, you will need to declare a lateinit var, i.e lateinit var logo: ImageView or you can initialize it as null i.e var logo: ImageView? = null and then later you can reassign as initented logo = findViewById(R.id.logo)

0

If you want to use this logo = findViewById(R.id.logo); in kotlin then you don't need to declare any extra variable you can simply use logo.setOnClickListener { } or anything similar kotlin will directly import it from your xml.(Note :- here logo is your imageView id).

All though if you want to declare any variable and initialize it later on then you can use lateinit var logo: ImageView or simply and nullable variable like var logo: ImageView? = null and initialize it later on. There are a lot of blogs and S.O Questions on google where you can find more about lateinit and nullable variables. Here is one of the S.O question you can refer.

WhiteSpidy.
  • 1,107
  • 1
  • 6
  • 28