-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;
    }
}
Max Jones
  • 133
  • 1
  • 7
  • 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`? – Mike M. Jul 03 '21 at 01:30

1 Answers1

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?