NPE When Using glfwWindowShouldClose (Kotlin) - nullpointerexception

So I've just started on a basic LWJGL 3 program using this tutorial. I've converted all the code into Kotlin to make it work, and everything seemed to be fine. Until I got to the very end where he utilizes glfwWindowShouldClose(window). I tried it the way he showed, and my own method of replacing the running variable with the function call itself. I even tried replacing it with true. Unfortunately, it doesn't appear to be working.
To clarify, what I mean is that when I use glfwWindowShouldClose(window) anywhere in my project, any call to an LWJGL function results in an NPE, even functions that have nothing to do with it:
Exception in thread "thingy" java.lang.NullPointerException
at org.lwjgl.system.Checks.check(Checks.java:98)
at org.lwjgl.glfw.GLFW.glfwSwapBuffers(GLFW.java:4206)
at main.Window.render(main.kt:39)
at main.Window.run(main.kt:15)
at java.lang.Thread.run(Thread.java:745)
The code I used for this example of the error is here:
class Window: Runnable {
private val thread = Thread(this, "thingy")
private val window: Long
override fun run() {
while (true) {
update()
render()
}
}
init { thread.start(); window = init() }
private fun init(): Long {
if (!glfwInit()) System.err.println("Couldn't initialize GLFW.")
glfwWindowHint(GLFW_RESIZABLE, 1)
val window = glfwCreateWindow(800, 600, "thingy", NULL, NULL)
if (window == NULL) System.err.println("Couldn't create a window.")
val vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor())
glfwSetWindowPos(window, 100, 100)
glfwMakeContextCurrent(window)
glfwShowWindow(window)
return window
}
private fun update() { glfwPollEvents() }
private fun render() { glfwSwapBuffers(window) }
}
If I remove the function call and replace it with false in the while statement, it works fine. Is it possible that the instance of my loop itself is causing problems, and the only way it doesn't throw an exception is if the loop never happens (false)?

You are missing some important calls, such as GL.createCapabilities()
I'd strongly suggest you to start from the HelloWord you find here
Ps: if you use kotlin, I have a lib that can give you a ready scenario in a couple of lines
with(glfw) {
init()
windowHint { context.version = "3.3"; profile = "core"; }
}
GlfwWindow(windowSize, title).apply { makeContextCurrent(); show(); }
GL.createCapabilities()

Related

Can't call a function from CountDownTimer object. What am I missing?

I'm going through Googles Kotlin Compose tutorials. One of the tasks is to build a game where you unscramble words. After completing it, I tried to improve the game on my own, and just can't figure out how to add a countdown timer to it. I want the program to skip a word when time runs out.
I'm a programming noob, it's not quite clear to me yet how classes and objects work and how they differ from functions.
The code for the timer at the moment:
object Timer: CountDownTimer(60000, 1000) {
override fun onTick(millisUntilFinished: Long) {
TODO("Not yet implemented")
}
override fun onFinish() {
skipWord() // <<----------- **Unresolved reference: skipWord**
}
}
Elsewhere in my code I have:
class GameViewModel : ViewModel() {
//....
fun skipWord() { // <<---------------- Function that skips to the next word
updateGameState(_uiState.value.score)
updateUserGuess("")
}
//.....
private fun pickRandomWordAndShuffle(): String {
// Continue picking up a new random word until you get one that hasn't been used before
if (currentLanguage == "English") {
currentWord = engWords.random()
} else {
currentWord = finWords.random()
}
setPointAmount()
Timer.start() // <<---------------Start a new countdown for a new word.
if (usedWords.contains(currentWord)) {
return pickRandomWordAndShuffle()
} else {
usedWords.add(currentWord)
return shuffleCurrentWord(currentWord)
}
}
}
Also, a separate problem: the .random() always uses the same seed and picks the same words to unscramble.
Change
object Timer: CountDownTimer(60000, 1000) {
...
to
val timer = object: CountDownTimer(60000, 1000) {
...
and put in into your GameViewModel class.
To solve random issue provide some seed to Random object, like:
var myRandom = Random(System.currentTimeMillis())
and then
currentWord = engWords[myRandon.nextInt(engwords.lastIndex)]

Can I return from lambda by invoking some function inside its body (non-local returns)

So I'm making regexes for collections (all quantifiers are possessive). It looks like this (keep in mind the example is overly simplified for readability's sake):
val mayBeAPerson: Boolean = "totally not a person"
.toList()
.matches { // this: PatternScope
one { it.isUpperCase() } // execution of lambda could end after this method
moreThan(0) { it.isLetter() }
one { it == ' ' }
lessThan(2) { // this: PatternScope
one { it.isUpperCase() }
one { it == '.' }
one { it == ' ' }
}
one { it.isUpperCase() }
moreThan(0) { it.isLetter() }
}
As you can see, execution of lambda passed to matches could end after first one, as the predicate passed to it doesn't match first character in List. And it indeed does end. However, my solution is the opposite of elegant, as it uses throwing an exception in one and catching it in matches.
fun List<Char>.matches(build: PatternScope.() -> Unit) = try {
val scope = PatternScope(iterator())
scope.build() // may throw MatchFailed
!scope.iterator.hasNext()
} catch (_: MatchFailed) {
false
}
class PatternScope(private val iterator: Iterator<Char>) {
inline fun one(predicate: (element: Char) -> Boolean) {
if (!iterator.hasNext() || !predicate(iterator.next())) {
throw MatchFailed("match failed")
}
}
.
. etc
.
}
It totally works, but I can't help but wonder: is there a better way? I do know throwing exceptions like this is just a fancy GOTO, and I could wrap all the methods of PatternScope in ifs, like this:
class PatternScope(private val iterator: Iterator<Char>) {
private var matchFailed = false
inline fun one(predicate: (element: Char) -> Boolean) {
if (!matchFailed) {
if (!iterator.hasNext() || !predicate(iterator.next())) {
matchFailed = true
}
}
}
inline fun moreThan(n: Int, predicate: (element: Char) -> Boolean) {
if (!matchFailed) {
// logic
}
}
.
. etc
.
}
Is it more elegant though? Now I'm invoking all the functions in lambda passed to matches, and I like it even less to be honest.
My real question is: is there even better way to do it? Some magic solution to return from lambda I don't even have real access to? Some non-local returns, but from functions lambda hasn't even see yet?
Can I return from lambda by invoking some function inside its body?
Edit
Just to clarify, let's say we have a lambda:
val lambda: () -> Unit = {
someMethod() // this should return from lambda (in some cases)
someOtherMethod() // this shouldn't be invoked
}
How should the body of someMethod look like, so that someOtherMethod does not even execute when the lambda is invoked? Is there any other way but making someMethod throw an exception and wrapping lambda in try-catch block like this:
try {
lambda() // throws
} catch (_: SomeThrowableIdk) { }
I don't see a better way, but please prove me wrong.
I assume you're actually using #PublishedApi since you have a private iterator and public inline functions that access it.
Since Kotlin doesn't have checked exceptions, it is against Kotlin convention to throw Exceptions for things that are not actually errors in the program (bugs). Your first approach feels a little hacky for this reason. Since your API has public inline functions, there's no way to totally encapsulate the exceptions. You could switch to non-inline functions and storing the steps in a collection to be run internally, but this is surely more runtime overhead than the inline functions or your second approach with if statements.
Your second approach is more like a typical builder, so I don't see the problem with it. Since your functions are inline, it's not like your compiled code has a bunch of unnecessary function calls. Just if statements. You could however add a helper function to clean up your code at all the sub-functions, though I'm not sure if this can extend to the complexity of your actual class:
class PatternScope(#PublishedApi internal val iterator: Iterator<Char>) {
#PublishedApi internal var matchFailed = false
#PublishedApi internal inline fun nextRequire(require: () -> Boolean) {
matchFailed = matchFailed || !require()
}
inline fun one(predicate: (element: Char) -> Boolean) = nextRequire {
iterator.hasNext() && predicate(iterator.next())
}
}
There's no way to do what you described in your edit. Non-local returns work only with lambdas. To support something like what you describe, Kotlin would need syntax for a special kind of function that has the ability to return from the function that calls it. A function like this would have to have a new kind of signature that also declares the return type of the type of function that is permitted to call it. There simply is no such syntax or function type like that in Kotlin.

Undetected throw declaration (Kotlin)

Let's have a function which just computes something in try-catch and returns the result:
private fun compute(): String {
return try {
// do some computation
// ...
"result"
} catch(t: Throwable) {
throw RuntimeException("Uups") // <-- GOAL: extract this to a dedicated method
}
}
I would like to extract the throw declaration to a separate function (which contains the my boilerplate code).
However, I'm unable to compile such setup in Kotlin.
A simplistic (and still uncompilable) version of the described problem:
private fun compute(): String {
return try {
// do some computation
// ...
"result"
} catch(t: Throwable) {
justThrow() // <-- NOT COMPILABLE, STRING EXPECTED
}
}
#Throws(RuntimeException::class)
private fun justThrow() {
// some boilerplate code
// ...
throw RuntimeException("Uups")
}
How write justThrow() method in Kotlin so that the whole code is compilable?
In Java this case would be detected by a compiler (I suppose).
Kotlin version: 1.4.21
You can declare the return type of your method as Nothing. This type can be used for any method that does not return normally. That might be because it will always throw an exception, or simply never returns at all, for instance because it contains an infinite loop.
private fun justThrow(): Nothing {
// some boilerplate code
// ...
throw RuntimeException("Uups")
}

Kotlin + Mockito + NullPointerException thrown when stubbing

Today I stumbled across a situation which I do not understand, possibly because of lack of insight into how mockito and mockito-kotlin work internally.
Given the code below, from my Kotlin beginner perspective, I have two pretty similar interface-methods. One returns Boolean, one String. Both are suspend functions in my example as in my real world situation my functions are too.
class ITestInterface {
suspend fun returnBoolean(): Boolean {
return true
}
suspend fun returnSomeString() : String {
return "String"
}
}
#Test
fun demoTest() {
val implMock = mock<ITestInterface> {
on {
runBlocking {
returnSomeString()
}
} doReturn "Hello"
on {
runBlocking {
returnBoolean()
}
} doReturn false
}
}
My observation is, when I run the test, like depicted above, I get the following error Message
com.nhaarman.mockitokotlin2.MockitoKotlinException: NullPointerException thrown when stubbing.
This may be due to two reasons:
- The method you're trying to stub threw an NPE: look at the stack trace below;
- You're trying to stub a generic method: try `onGeneric` instead.
at com.nhaarman.mockitokotlin2.KStubbing.on(KStubbing.kt:72)
at com.rewedigital.fulfillment.picking.components.substitute.DemoTest.demoTest(DemoTest.kt:30)
[...]
Experiments showed that
the behavior is only shown by the Boolean returning function, not by returnSomeString()
removing the suspend keyword fro the returnBoolean function makes the error go away
using onGeneric as suggested in the error message also makes the error go away
Could anybody explain why this is happening? To what extend do we have to do with generics here? And what would be the correct way of solving the issue in our real application? Having a bunch of on {} and some onGeneric {} ?
Thanks for your help!
You should use the onBlocking method to properly mock the suspend function
Please try the following code:
#Test
fun demoTest() {
val implMock = mock<ITestInterface> {
onBlocking {
returnSomeString()
} doReturn "Hello"
onBlocking {
returnBoolean()
} doReturn false
}
runBlocking {
// Execute your code here
assertThat(implMock.returnSomeString()).isEqualTo("Hello")
assertThat(implMock.returnBoolean()).isEqualTo(false)
}
}

Is there even a simpler way to express anonymous classes in Kotlin?

I translated this Java
new Thread("Cute Thread") {
public void run() {
int a = 3;
}
}.start();
to this Kotlin
object : Thread("Cute Thread") {
override fun run() {
val a = 3
}
}.start()
But I feel that there is a simpler way of doing this, however I can't find any examples.
I've tried
Thread("Cute Thread") { val a = 3 }.start()
But with no success...
PS. I know that starting a Thread like this is a bad practice.
There's no different way to implement an anonymous class (except SAM conversions).
But you can still simplify your code by:
Thread({ val a = 3 }).start()
or with thread name:
Thread({ val a = 3 }, "Cute Thread").start()
One issue here is that the Thread class constructor has parameters in a bad order for Kotlin. For Runnable you can easily use a SAM conversion (a single method interface can be treated as a lambda) but because the lambda is not the last parameter it looks kinda clunky. In the case where there is only one parameter it is fine:
Thread { val a = 3 }.start()
However with more than one parameter, they are backwards causing this uglier syntax with the lambda as a parameter inside the parenthesis:
Thread({ val a = 3 }, "some name").start()
Instead you should use the Kotlin stdlib function thread()
With that function you have simpler syntax of:
// create thread, auto start it, runs lambda in thread
thread { val a = 3 }
// create thread with given name, auto start it, runs lambda in thread
thread(name = "Cute Thread") { val a = 3 }
// creates thread that is paused, with a lambda to run later
thread(false) { val a = 3 }
// creates thread that is paused with a given name, with a lambda to run later
thread(false, name = "Cute Thread") { val a = 3 }
See also: thread() function documentation
You code is absolutely correct. The only way to simplify it is it extract the logic into a function and then reuse it:
fun newThread(name: String, block: () -> Unit): Thread {
return object : Thread(name) {
override fun run() = block()
}.start()
}
Usage:
newThread("Cute Thread") {
val a = 3
}
If you want to extend/implement some class/interface in your anonymous class there is no other way than:
object: Thread("Name"){
//...
}.start()
The simplest possible construction is of course:
val adhoc = object{
// some code here
}
but there are no simpler way to do this.
Documentation, but You probably read that.