What's the difference between KotlinNullPointerException and Java's NullPointerException - kotlin

As Kotlin doesn't allow for implicit null values/variables, was KotlinNullPointerException introduced to explicitly denote NPE caused by !!? Is that the only purpose of this child class of NullPointerException?

There is no real difference between a KotlinNullPointerException and JavaNullPointerException.
Here is how:
KotlinNullPointerException is an open class that extends NullPointerException Now this NullPointerException is a typealias of java.lang.NullPointerException.
public open class KotlinNullPointerException : NullPointerException {
constructor()
constructor(message: String?) : super(message)
}
This is a line extracted from TypeAlias.Kt
#SinceKotlin("1.1") public actual typealias NullPointerException = java.lang.NullPointerException
Now, if we see the declaration of java.lang.NullPointerException, we are taken to a Java.lang class that extends RuntimeException.
public
class NullPointerException extends RuntimeException {
private static final long serialVersionUID = 5162710183389028792L;
/**
* Constructs a {#code NullPointerException} with no detail message.
*/
public NullPointerException() {
super();
}
/**
* Constructs a {#code NullPointerException} with the specified
* detail message.
*
* #param s the detail message.
*/
public NullPointerException(String s) {
super(s);
}
}
In Kotlin, to make some declaration of nullable type, you have to explicitly allow it by appending ? at the end of declaration type. Example:
var nullableString: String? = null
This is a simple way of saying that this variable could be null anytime, so if you try to access this variable from any part of your code, it will throw error and will force you to take measures to prevent NPE either using !!(crash if null) or ?(skip if null).
It's just a way to make it look more like 'Kotlin'.

As of version 1.3, Kotlin throws KotlinNullPointerException only in case of a failed !! operator check. This distinguishes it from the other cases where NullPointerException can be thrown, for example, when accessing non-initialized members during class construction.
Note, however, that there are plans to remove this distinction in Kotlin 1.4: all such failed checks will throw just NullPointerException, so its inheritor KotlinNullPointerException will become unused. You can read more about that in the announce blog post of 1.3.50 version release: https://blog.jetbrains.com/kotlin/2019/08/kotlin-1-3-50-released/

Related

Verifying method call with enum in Kotlin

I'm trying to verify that a method is called with a given argument. That argument is a non-nullable enum type. So I get the exception eq(SomeEnum.foo) must not be null. Here is a sample what I'm trying to do:
enum class SomeEnum {
foo, bar
}
open class MyClass {
fun doSomething() {
magic(SomeEnum.foo)
}
internal fun magic(whatever: SomeEnum) {}
}
#Test
fun mockitoBug() {
val sut = spy(MyClass())
sut.doSomething()
verify(sut).magic(eq(SomeEnum.foo))
}
Capturing does not work too. What can I do or is that really a bug as I assume?
Because Mockito was designed for Java, it doesn't play well with Kotlin's null checks. A good solution is to use the mockito-kotlin extensions library: https://github.com/mockito/mockito-kotlin
It includes Kotlin versions of the matchers that won't return null. Add a dependency on mockito-kotlin and just make sure to import the Kotlin versions instead of the Java ones.

Kotlin compiler issue with overriding of Java final function in Kotlin

I’m dealing with following issue with Kotlin/Java Compiler.
Imagine following scenario: let First be a Java class with a final function and Second be a Kotlin class extending First with a function of the same name like the final function in First class, example:
// Java class
class First {
final void foo() { }
}
// Kotlin class
class Second: First() {
fun foo() { }
}
Obviously, it’s wrong because the final function foo() can not be overridden. However, compilation pass successfully and in run-time I get java.lang.LinkageError: Method void Second.foo() overrides final method in class First.
Is this correct behavior of compiler? I supposed that there will be some validations for this case. Thank you!

Lombok #NonNull Does Not Apply Check on Return Type

IDE: Intellij
I am using Lombok's NonNull annotation to automatically generate Null Pointer Checks and throw exceptions on Method Arguments and Return Types.
On writing Unit Tests, the 'null' method Arguments do throw the exception, but the null return types do not throw exceptions.
import lombok.NonNull;
public #NonNull String function( #NonNull String input) {
return null;
}
The following Test fails:
#Test
public void
whenReturnTypeIsNull_ThenIllegalArgumentExceptionIsThrown(){
assertThrows(IllegalArgumentException.class, ()-> testClass.function() );
}
With the Message:
Expected java.lang.IllegalArgumentException to be thrown, but nothing was thrown
The Lombok project documentation clearly states that the NonNull annotation allows to generate boilerplate null-checks for constructor and method arguments:
You can use #NonNull on the parameter of a method or constructor to have lombok generate a null-check statement for you.
Thus you should programatically check you return value invariants, including being non-null.

How does JUnit mask checked exceptions?

JUnit 5 masks checked exceptions with this code:
public static RuntimeException throwAsUncheckedException(Throwable t) {
Preconditions.notNull(t, "Throwable must not be null");
ExceptionUtils.throwAs(t);
// Appeasing the compiler: the following line will never be executed.
return null;
}
#SuppressWarnings("unchecked")
private static <T extends Throwable> void throwAs(Throwable t) throws T {
throw (T) t;
}
In the call to throwAs, how does Java decide on the value of the type variable T?
More importantly, how does this code mask a checked exception?
I believe that T is inferred to be RuntimeException. I'm inferring that from making the following change to the code of throwAsUncheckedException:
var o = ExceptionUtils.throwAs(t);
... and changing the declaration of throwAs to:
private static <T extends Throwable> T throwAs(Throwable t) throws T
(Note that I'm using var from Java 10 to let the compiler infer the type without any further information being provided.)
After compiling and then using javap -c you can see that there's a checkcast to RuntimeException:
invokestatic #2 // Method throwAs:(Ljava/lang/Throwable;)Ljava/lang/Throwable;
checkcast #3 // class java/lang/RuntimeException
astore_1
That makes it fine for throwAs not to declare that it throws anything else - it's only calling a method that declares that it throws T, so RuntimeException in this case.
Further somewhat specious evidence for this is in JLS section 18, which includes this line:
Otherwise, if the bound set contains throws αi, and each proper upper bound of αi is a supertype of RuntimeException, then Ti = RuntimeException.
No other concrete exception types, or Throwable, are mentioned in that section. Unfortunately I find section 18 pretty much impenetrable, so this is really more of a "yes, that vaguely supports my theory" rather than good evidence.
In this particular case, I believe it would actually be fine (and simpler in terms of understanding) for the throwAsUncheckedException method to just specify the type argument explicitly:
ExceptionUtils.<RuntimeException>throwAs(t);
So that's how the compiler is molified. It thinks that only RuntimeException will be thrown. The actual value thrown is whatever's passed in though. The cast to T is ignored for all the normal type erasure reasons... if you change the code to actually cast to RuntimeException, it will fail for any checked exception. That's why it needs to be a generic method: to include a cast that satisfies the compiler without really casting at execution time.
The JVM allows this because as far as I'm aware, checked exceptions are purely a compiler aspect, and there's no validation for them in the JVM itself. It just knows about throwing exceptions.

Why do I get a compilation error when calling println method in the class body? #Java

class Test {
int a = 100;
System.out.println(a);
}
class Demo {
public static void main(String args[]) {
Test t = new Test();
}
}
I'm new to programming. I found this code when I'm practicing. I don't understand why I'm getting this error.
Here is the error I'm getting.
Demo.java:3: error: <identifier> expected
System.out.println(a);
^
Demo.java:3: error: <identifier> expected
System.out.println(a);
^
2 errors
Compilation failed.
Can you guys explain why I'm getting this error?
You can't call a method directly from the java class body.
Create a constructor in your Test class, and put the print in it :
class Test {
int a = 100;
public Test() {
System.out.println(a);
}
}
Note that if for some reason you really want a statement to be executed when the class is loaded without using a constructor, you can define a static block, here an example :
class Test {
static int a = 100;
static {
System.out.println(a);
}
}
However, this is just for reference and really not needed in your case.
From Declaring Classes in the Java tutorial:
In general, class declarations can include these components, in order:
Modifiers such as public, private, and a number of others that you will encounter later.
The class name, with the initial letter capitalized by convention.
The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
The class body, surrounded by braces, {}.
You can't make any function calls outside of a method declaration.