Reputation: 219
This is my main class:
package com.example.myProject
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.GridLayout
import androidx.core.view.marginLeft
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
var level : Int = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//...
var piece = Piece(this, 50)
}
}
I also have second class:
data class Piece(
var con: Context,
var size : Int
) {
init {
//...
//here I want to increment attribute level of the main class
con.level++
}
}
However, I can't access this attribute from there, even though I sent context as a parameter. Any idea what am I doing wrong?
Upvotes: 0
Views: 504
Reputation: 181725
The Context
class doesn't have a level
attribute, even though the concrete type MainActivity
does. So take a reference to a MainActivity
instead:
data class Piece(
var con: MainActivity,
var size : Int
) {
This creates a circular dependency between MainActivity
and Piece
, so it could be considered a code smell. Without more context, it's hard to say what a better solution would look like.
Upvotes: 1