Reputation: 9
I've started learning Android.
I can't use if
in Kotlin because I saw this error
Expecting member declaration
can you help me ??
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
var fixedIncome : Int = 50
var tips : Int = 20
var income : Int = fixedIncome + tips
if(tips == 0){
Log.d("tag", "You have not recieved any tips today")
} else {
Log.d("tag", "You have recieved some tips today")
}
}
Upvotes: 0
Views: 2163
Reputation: 8191
you can't write:
if(tips == 0){
Log.d("tag", "You have not recieved any tips today")
}else{
Log.d("tag", "You have recieved some tips today")
}
outside the scope of a method. You're outside the onCreate
method, you're essentially writing this in the class of MainActivity
, so change this to:
var fixedIncome : Int = 50
var tips : Int = 20
var income : Int = fixedIncome + tips
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if(tips == 0){
Log.d("tag", "You have not recieved any tips today")
}else{
Log.d("tag", "You have recieved some tips today")
}
}
OR, initialize and use everything in onCreate
:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var fixedIncome : Int = 50
var tips : Int = 20
var income : Int = fixedIncome + tips
if(tips == 0){
Log.d("tag", "You have not recieved any tips today")
}else{
Log.d("tag", "You have recieved some tips today")
}
}
As a side note:
because you're doing var tips : Int = 20
and never changing tips
, you might consider using val tips : Int = 20
to indicate that it is a value, not a variable.
Upvotes: 2