Issue
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*/
}
}
}
Solution
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
Answered By - Tomas Hula
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.