How can I create null class object in Kotlin? - java

In java, we can declare a null class object like this
VideoRecord videoRecord;
After that, we can check if it is null or not
if (videoRecord == null){
videoRecord = new VideoRecord();
}
I am new to Kotlin and I would like to do the same thing in Kotlin. I have tried this code below.
lateinit var videoRecord1:VideoRecord
if (videoRecord1 == null){
videoRecord1 = VideoRecord()
}
But it gives me a warning like the condition videoRecord1 == null is always false. How can I make the same thing in Kotlin?

var videoRecord: VideoRecord? = null
you can initial its variable like this
nullable reference : https://kotlinlang.org/docs/reference/null-safety.html

Depending on what you're trying to achieve, e.g. lazy initialization then this may be more suitable for you than the answer given by andika_kurniawan:
val videoRecord: VideoRecord by lazy { VideoRecord() }
This will lazily initialize videoRecord the first time it is accessed.
The advantage of this way is that you don't have to check for null when accessing videoRecord, because it cannot be null. This simplifies the usage of that variable significantly. Additionally you can mark videoRecord as val, meaning it is final, so it cannot be overwritten.
The example shown by #andika_kurniawan:
var videoRecord: VideoRecord? = null
Has some caveats and disadvantages:
You always have to check that videoRecord is not null (and it gets tedious), see this example:
if (videoRecord != null) {
videoRecord.callAMethod()
}
The above will not work, because videoRecord defined as nullable, so you need to use the !! operator to tell kotlin that you're sure that the variable is not null:
if (videoRecord != null) {
videoRecord!!.callAMethod()
}
You can of course use other idioms, like the null-safe operator ?.
videoRecord?.callAMethod()
Or the already mentioned !! operator (which throws an exception when it is null) but this time without a null check:
videoRecord!!.callAMethod()
You may also use local variables, which simplify the usage (a little bit):
val videoRecord = videoRecord
if (videoRecord != null) {
videoRecord.callAMethod()
}
The variable is not final, so nothing stops you from doing this somewhere in your code:
videoRecord = null
You have to initialize it somewhere, so if you have multiple methods accessing videoRecord you first have to initialize it if it hasn't already been, introducing unnecessary redundancy.

In kotlin, declaration of variable is different from java as kotlin is null safe language. You have to declare variable nullable. Only then its value can be null.
You can declare it as below
var videoRecord: VideoRecord? = null
To access nullable values you have to use !! or ? with variable names.

Related

Is there any built-in in method in spring to write an empty/null check method?

I wrote this code, and I was wondering if there was a built-in method from spring that does the same thing as this method.
public static String map(String value) {
return value != null && value.isEmpty() ? null : value;
}
I found ObjectUtil, but it didn't have any method that has the same functionality.
I would appreciate any suggestion!
Looking at your code seems you just map the empty string to null instead of avoiding it at all.
public static String map(String value) {
return value != null && value.isEmpty() ? null : value;
}
If value is null it return value so null, if it's empty it returns null again.
If your intent is to avoid null values, you should introduce the NullObject pattern.
On java 8+ use the Optional as it is the same, but natively supported by the language.
As already shown in comments by Jan Schumacher, it helps you to easely filter the value further.
With your function you still need a null check, but using Optional you don't need it anymore and the code is much clearer.
You can even use the #NotNull annotation in the method signature, to help enforce null values to be propagated when not expected.

Why is call to put() failing to compile in Kotlin when it compiles in Java with similar code

I have the following function in java and I need to convert it to Kotlin.
#Override
public void afterTextChanged(Editable s) {
if (s != null && !"".equals(s.toString())) {
int position = (Integer) mHolder.numEdit.getTag();
// Saved to the data variable when the data changes
mData.get(position).put("list_item_inputvalue",
s.toString());
}
}
This is the equivalent Kotlin code that I've created:
override fun afterTextChanged(s: Editable?) {
if (s != null && "" != s.toString()) {
val position = mHolder.numEdit!!.tag as Int
// Saved to the data variable when the data changes
mData?.get(position).put("list_item_inputvalue", s.toString())
}
}
The compiler doesn't like the call to .put(). The variable mData in Java is:
private List<Map<String, String>> mData;
and Kotlin:
var mData: List<Map<String, String>>? = null
Why doesn't the compiler like the conversion of put in Kotlin?
UPDATE:
println(mData) = [{list_item_inputvalue=0}, {list_item_inputvalue=1},...]
println(mData?.get(position)) = {list_item_inputvalue=8}
Code in Java
Your problem centers around this statement in your question:
var mData: List<Map<String, String>>? = null
In Kotlin, the Map type is immutable, and so has no .put() method. That's the problem you're running up against. To fix it, just change this statement to:
var mData: List<MutableMap<String, String>>? = null
A second '?' is necessary after mData?.get(position) because that statement will return null if mData == null. That is, that statement returns a type of MutableMap<String, String>? even though the .put() by itself would return a type of MutableMap<String, String>.
To summarize...if you create a list of mutable maps, the compiler will then be happy with the statement:
mData?.get(position)?.put("list_item_inputvalue", s.toString())
Initially, it wasn't clear what exactly the question was, so let's start with the various syntax elements in here:
!!: the not-null assertion operator (!!) converts any value to a non-null type and throws an exception if the value is null. We can write b!!, and this will return a non-null value of b (e.g., a String in our example) or throw an NPE if b is null (quoted from kotlinlang)
[position]: Square brackets are translated to calls to get and set with appropriate numbers of arguments. (again, from kotlinlang) In other words:
that is simply "syntactic" sugar: you can treat a collection (probably a list) as an array. Meaning: instead of writing down get(index) to denote an element in a list, you can just go [index] as if that were an ordinary array.
Kotlin allows to use someMap[someKey] for its own maps. So, to answer the initial question, a further "conversion" could replace the call to put() via square brackets as well.
In that case, you have to be aware of the fact that Kotlin maps are immutable by default (so when using mapOf() you get a immutable map). Or, if you want to have a mutable Kotlin map "around" a Java map, you have to use mutableMapOf()!

java.util.Objects.isNull vs object == null

As you know, java.util.Objects is
This class consists of static utility methods for operating on objects.
One of such methods is Objects.isNull().
My understanding is that Objects.isNull() would remove the chance of accidentally assigning a null value to object by omitting the second =.
However, the API Note states:
This method exists to be used as a Predicate, filter(Objects::isNull)
Would there be any reason/circumstance for which I should use object == null over Objects.isNull() in an if statement?
Should Objects.isNull() be confined to Predicates exclusively?
should use object == null over Objects.isNull() in a if statement?
If you look at the source code of IsNull method,
/* Returns true if the provided reference is null otherwise returns false.*/
public static boolean isNull(Object obj) {
return obj == null;
}
It is the same. There is no difference. So you can use it safely.
Objects.isNull is intended for use within Java 8 lambda filtering.
It's much easier and clearer to write:
.stream().filter(Objects::isNull)
than to write:
.stream().filter(x -> x == null).
Within an if statement, however, either will work. The use of == null is probably easier to read but in the end it will boil down to a style preference.
Look at the source:
public static boolean isNull(Object obj) {
return obj == null;
}
To check for null values, you can use:
Objects.isNull(myObject)
null == myObject // avoids assigning by typo
myObject == null // risk of typo
The fact that Objects.isNull is meant for Predicates does not prevent you from using it as above.
Would there be any reason/circumstance for which I should use object == null over Objects.isNull() in a if statement?
Yes, one reason is to keep the code simple. Within if statement object == null is clear and well known. It can not lead to any misbehavior if for example there is a typo.
My understanding is that Objects.isNull() would remove the chance of accidentally assigning a null value to object by omitting the second =.
If there is an if (object = null) {} with omitted = it will not compile or it will generate warning in case of Boolean object! Actually there is no reason to use Objects.isNull(object) over object == null within if statement. Here are the two variants side by side:
if (object == null) {
}
if (Objects.isNull(object)) {
}
Should Objects.isNull() be confined to Predicates exclusively?
It could be said yes, it is confined to Predicates exclusively, although there is no technical hurdle to use the Objects.isNull() everywhere.
From the public static boolean isNull(Object obj) method's javadoc:
#apiNoteThis method exists to be used as a java.util.function.Predicate, filter(Objects::isNull)
So if you use the method as not a predicate you are actually using a more complex and cumbersome expression compared to the simple object == null.
Here is a snippet to compare the benefit of Objects.isNull(object)
List<String> list = Arrays.asList("a", "b", null, "c", null);
// As ready-made predicate
long countNullsWithPredicate = list.stream().filter(Objects::isNull).count();
// Lambda
long countNullsWithLambda = list.stream().filter(object -> object == null).count();
// Reimplement the Objects::isNull predicate
long countNullsWithAnonymous = list.stream().filter(new Predicate<Object>() {
#Override
public boolean test(Object obj) {
return obj == null;
}
}).count();
Semantically there is no difference but for readability I prefer the following over whatever == null:
import static java.util.Objects.isNull;
// Other stuff...
if(isNull(whatever)) {
}

Standard approach to assign default value in Java

Often I invoke alien methods which might return a null value. In order to avoid simple null checks like
if (myVariable != null) {
// do something
}
I sometimes assign a default value, like this:
myVariable = (myVariable == null) ? defaultValue : myVariable;
This seems a little bit redundant in Ruby for instance, there is the ||= operator
I am not asking for such an operator, but my standard approach with the ternary operator seems a little bit redundant or maybe also confusing?
What better ways are there?
Try this:
if (myVariable == null) {
myVariable = defaultValue;
}
If the alien method maybe return null value, it should note about null return value in method's Java docs. The client uses that alien method must check, but no way, the return value.
The simple way to do this:
retVal = alienMethod();
if (retVal == null) {
retVal = defaultVal;
}
If you still want to avoid checking null value, the method that return the value must be in responsible for return default value. But what is your default value? Depend on your return type, you can create a dummy class to represent your default value instead of returning null value.
There are no better/shorter/nicer ways to do it....
There was talk about introducing a '?' operator for null values in Java 7, but the concept got shifted out of the release.... maybe for Java 8 ?
https://blogs.oracle.com/darcy/entry/project_coin_final_five
http://viralpatel.net/blogs/2009/10/null-safe-type-java-7-nullpointerexception.html
http://mail.openjdk.java.net/pipermail/coin-dev/2009-March/000047.html
In general, there is no "elegant" way. If the variable is a field of your class, you can do it in the setter or getter. But proper javadocs (which I don't show below!) are important to explain what happens to nulls. e.g.
public void setFoo(Foo foo) {
this.foo = foo != null ? foo : DEFAULT_FOO;
}
public Foo getFoo() {
return foo != null ? foo : DEFAULT_FOO;
}
You can wrap the assigning of a default value into a small utility function and put it in a helper class. For variables of type String, this would look like this:
public static String unNull(String val,String defVal) {
return (val==null ? defVal : val);
}
Then, in your code you can just write
myVariable = unNull(alienMethod(),defaultValue);
Using a static import, you can do without prefixing the static method's name with the class name.
You can also make a generic method to handle this (to template the type of both arguments and the return type), but I'm not sure it would work without an additional parameter of type Class.
There is finally a better way to do it: Optional in Java 8. Instead of
Foo myVariable = bar();
myVariable = (myVariable == null) ? defaultValue : myVariable;
where bar() may return null, now you do
Foo myVariable = Optional.ofNullable(bar()).orElse(defaultValue).get()

Is there a way to check if a variable is defined in Java?

In my app in android I need to check if a variable has been defined yet so I dont get a null pointer exception. Any way around this?
The code won't compile if you try to use an undefined variable, because, In Java, variables must be defined before they are used.
But note that variables can be null, and it is possible to check if one is null to avoid NullPointerException:
if (var != null) {
//...
}
if (variableName != null)
{
//Do something if the variable is declared.
}
else
{
//Do something if the variable doesn't have a value
}
I think that should do it.
It will throw an exception if we try to use an undefined variable in java. To over come these make use of wrapper Class and assigned it to null.
Integer a = null; //correct
int a = null;//error

Categories

Resources