-1

This java code, is calling isKeyDown method which is in the Input kotlin class and it is throwing

Non-static method 'isKeyDown(int)' cannot be referenced from a static context

public Boolean run() {
    Input.isKeyDown(GLFW.GLFW_KEY_ESCAPE); 
    }
 }

I tried putting the kotlin method in a companion object. the only thing is the isKeyDown method loses scope of the key[ ] array which is an in the scope of the whole class

class Input{
   private val keyArray :
        BooleanArray =
    BooleanArray(GLFW.GLFW_KEY_LAST)



   /**/
  companion object{
       @JvmStatic
       fun isKeyDown(key: Int): Boolean{
           return keyArray[key] /*Unresolved reference: keyArray*/
       }

   }
 }
Tygris
  • 25
  • 4
  • 1
    It's a little unclear what you actually want to happen. If you don't want to use a companion object, then you'll need an _instance_ of `Input` to invoke `isKeyDown` on. Or perhaps you want to make `Input` an object (i.e., `object Input { ... }`). – Slaw Jun 25 '22 at 09:03
  • Look I meant whe i put the isKeyDown in a companion object, the isKeyDown method cannot find the keys[] array anymore....it gives unsolved reference – Tygris Jun 25 '22 at 09:17
  • Oh i put it in an object, with the @JvmStatic annotation it worked, thank you. if you want you can answer and i will accept it :)) – Tygris Jun 25 '22 at 09:21

1 Answers1

1

It seems, that you don't understand a static context.

In the first example, you have your isKeyDown(int) method as a class member, meaning, that if you want to call that method, you have to create a new instance of the Input class and call the method on it afterwards. Example:

public Boolean run() {
  Input input = new Input()
  return input.isKeyDown(GLFW.GLFW_KEY_ESCAPE);
}

In the second example, you are trying to access a class member from its's static context, which is not possible and it makes sense, once you understand static.

Your other solution is to make the Input class a singleton. That means there's only one istance of the class in the whole application and then you access the object as a static class from java. You can do that by using the kotlin object keyword. Example:

object Input
{
    private val keyArray: BooleanArray = BooleanArray(GLFW.GLFW_KEY_LAST)

    @JvmStatic
    fun isKeyDown(key: Int): Boolean {
        return keyArray[key]
    }
}

and then your java caller method:

public Boolean run() {
  return Input.isKeyDown(GLFW.GLFW_KEY_ESCAPE);
}

Based on what I see, the second option is probably the one you want to use. Here you can read about java static modifier: https://www.baeldung.com/java-static

Tomas Hula
  • 26
  • 2
  • thanks for explaining my friend, yes I will look into static im not that familiar with object orientation, thank you – Tygris Jun 25 '22 at 09:50