0

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?

1
  • Why do you want to do it that way? Why not adding one on the activity? Commented Oct 19, 2020 at 12:19

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.