-1

I am new to kotlin and android studio's (which I am using), so this is very simple, but I ran into this problem while working on a tutorial

The issue is very simple:

I have two kotlin classes (MainActivity and why). Why contains a function test that I want to call in MainActivity.

How do I do this?

In the tutorial I simply call it like so in MainActivity

why.test()

(full code below)

But when I try to run doing this I get the error:

"Unresolved reference: test on line 13" (where I call test).

Why is this happening? How do I get this to work?

Code:

MainActivity class:

package com.example.tester

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        work()
    }
    private fun work() {
        why.test()
    }
}

test function in why class: (test does nothing in this example)

package com.example.tester

class why {
    fun test() {
        var i = 0;
    }
}
1
  • Are you sure the tutorial didn't have why().test()? With parentheses right after why? Or, did they possibly have why declared as an object instead of a class? Commented Jul 3, 2021 at 1:30

1 Answer 1

2

I think "test" should be static (or create object of why), like so:

package com.example.tester

class why {
   companion object { 
     fun test() {
        var i = 0;
      }
   }
}

See What is the equivalent of Java static methods in Kotlin?

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.