I used takeIf for conditional judgment, but still encountered the following exception:
java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
at jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)
at java.util.Objects.checkIndex(Objects.java:359)
at java.util.ArrayList.get(ArrayList.java:434)
at com.minecraft.mc_chat.MainViewModel$callback$1.msgCallback(MainViewModel.kt:213)
at com.minecraft.mc_chat.nsd.FindBonjourTool$createDiscoverListener$1$onServiceFound$1.onServiceResolved(FindBonjourTool.kt:122)
at android.net.nsd.NsdManager$ServiceHandler.lambda$handleMessage$11(NsdManager.java:1029)
at android.net.nsd.NsdManager$ServiceHandler$$ExternalSyntheticLambda2.run(Unknown Source:4)
at android.net.nsd.NsdManager$$ExternalSyntheticLambda2.execute(Unknown Source:0)
at android.net.nsd.NsdManager$ServiceHandler.handleMessage(NsdManager.java:1029)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:230)
at android.os.Looper.loop(Looper.java:319)
at android.os.HandlerThread.run(HandlerThread.java:67)
I don’t know why this happened, was it because I used takeIf incorrectly?
list.takeIf { it.size == 1 }?.let {
stopScan()
val ip = it[0].host.hostAddress
startChatClient(ip, port)
return
}
If the condition is false, then the subsequent code will not be executed, why do exceptions still occur?
If there is a correct method, please let me know
New contributor
ggboundzhl is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.