A quick comparison to Java code

Let's take a moment to write the same class in Java and see the differences provided by Kotlin:

public class Producer {
@Inject
InitialContext initialContext;

public String sendMessage(String message) {
try {
Queue queue = (Queue)initialContext.lookup("jms/PointToPointQueue");
ConnectionFactory connectionFactory = (ConnectionFactory)
initialContext.lookup("jms/__defaultConnectionFactory");
JMSContext jmsContext = connectionFactory.createContext();
jmsContext.createProducer()
.send(queue, message);
jmsContext.close();
}catch (NamingException e) {
e.printStackTrace();
}
return "Message sent";
}
}

Note how the code in Kotlin looks more expressive compared to Java. We don't need the type declaration, we just use either val or var and the type is inferred from the context. This means that no explicit type casting is required; Kotlin provides us with an elegant syntax to express the type.

Also, note that the initialContext can be null. If we are not injecting initialContext, we end up with a NullPointerException. We then add the null check in the code. If we forget to add the null check and the context is not initialized, the compiler won't complain but the code will fail at runtime.  

Kotlin code is more mature in this respect. The compiler forces us to add null checks using ?. before accessing a variable that is declared as null:

@Inject
private var initialContext: InitialContext? = null

Let's say we are trying to use this initialContext directly without the value being injected, as follows:

val queue = initialContext.lookup("jms/PointToPointQueue") as Queue

This code fails to compile and gives the following error:

Error:(15, 39) Kotlin: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type InitialContext?

Before using initialContext, the compiler forces us to add a null check or to initialize the variable. This way, type safety is guaranteed and possible runtime errors are reduced.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset