What is opposite to 'in' condition in Kotlin - '!` mark equivalent to Java - kotlin

In Java we do use ! in case we want to say NOT. But what should I use in Kotlin if I follow some range condition.
if( item in 5..10)
So here I want to say if item NOT in 5..10 ?? what is the proper construction?

You can use !in operator:
if (item !in 5..10)
See documentation for a full list of operators:
https://kotlinlang.org/docs/operator-overloading.html#in-operator
https://kotlinlang.org/docs/keyword-reference.html#hard-keywords

Related

ArgumentMatcher for Kotlin

I'm trying to use ArgumentMatcher in my tests. I do next:
Mockito.`when`(someRepository.save(
argThat { it.name == someName } // Here I want to do mock for all objects with name someName
)).thenReturn(save(someEntity))
And I get next error: Type inference failed: Not enough information to infer parameter T in fun when(p0: T!): OngoingStubbing!
How properly write ArgumentMatcher in Kotlin?
I strongly recommend using nhaarman's mockito-kotlin instead of vanilla Mockito. It has numerous advantages that allow it to be used with fewer issues in Kotlin as Mockito is designed for use in Java. You can see this guide for how to use argument matchers in Kotlin. Your example will look very similar, but should have less issues with type inference.
I found a solution by adding ArgumentMatcher from java class. My IDE converted it to Kotlin:
In java:
Mockito.when(someRepository.save(ArgumentMatchers.argThat(entity-> entity.getName().equals("someName")
&& entity.getDescription().equals("somedescritpion")
))));
In Kotlin:
Mockito.`when`<Any>(someRepository.save(ArgumentMatchers.argThat { (name, _, description, ) ->
(name == "someName" && description == "somedescritpion"
)
}))
Note: You should add _ if you have some fields which you don't want to consider in the matcher.
Use the someRepository.save(Mockito.any<String>()) . That would not care about what argument you are passing as long as it is a String. Empty values count too.

What is the difference between not-null checks in Kotlin?

There are some ways to fulfill a null-checking in Kotlin:
1.
if(myVar != null) {
foo(myVar)
}
2.
myVar?.let {
foo(it)
}
3.
myVar?.run {
foo(this)
}
What are the difference between these ways?
Are there any reasons (performance, best practice, code style etc.) why I should prefer on way over the other?
!! is to tell the compiler that I am sure the value of the variable is not null, and if it is null throw a null pointer exception (NPE) where as ?. is to tell the compiler that I am not sure if the value of the variable is null or not, if it is null do not throw any null pointer.
Another way of using a nullable property is safe call operator ?.
This calls the method if the property is not null or returns null if that property is null without throwing an NPE (null pointer exception).
nullableVariable?.someMethodCall()
All three code are behave same null check in operation-wise.
?. is used for chain operations.
bob?.department?.head?.name // if any of the properties in it is null it returns null
To perform a chain operation only for non-null values, you can use the safe call operator together with let
myVar?.let {
foo(it)
}
the above code is good for code style and performance
more details refer Null Safety
The ways 2 and 3 are more idiomatic for Kotlin. Both functions are quite similar. There is little difference with argument passing.
For example, we have a nullable variable:
var canBeNull: String? = null
When you working with T.run you work with extension function calling and you pass this in the closure.
canBeNull?.run {
println(length) // `this` could be omitted
}
When you call T.let you can use it like lambda argument it.
canBeNull?.let {
myString -> println(myString.length) // You could convert `it` to some other name
}
A good article about Kotlin standard functions.
All three are roughly equivalent.
The if case is more like most other languages, and so many developers may find it easier to read.
However, one difference is that the if case will read the value of myVar twice: once for the check, and again when passing it to foo(). That makes a difference, because if myVar is a property (i.e. something that could potentially be changed by another thread), then the compiler will warn that it could have been set to null after the check. If that's a problem (e.g. because foo() expects a non-null parameter), then you'll need to use one of the other cases.
For that reason, the let case has become fairly common practice in Kotlin. (The run case does just about the same thing, but for some reason isn't as popular for this sort of thing. I don't know why.)
Another way around it is to assign myVar to a temporary value, test that, and then use that. That's also more like other languages, but it's more verbose; many people prefer the conciseness of the let case — especially when myVar is actually a complicated expression.
The examples in your question don't show the true reason to decide.
First of all, since you're not using the return value of foo, you should use neither let nor run. Your choice is between also and apply.
Second, since you already have the result you want to null-check in a variable, the difference fades. This is a better motivating example:
complexCall(calculateArg1(), calculateArg2())?.also {
results.add(it)
}
as opposed to
val result = complexCall(calculateArg1(), calculateArg2())
if (result != null) {
results.add(result)
}
The second example declares an identifier, result, which is now available to the rest of the lexical scope, even though you're done with it in just one line.
The first example, on the other hand, keeps everything self-contained and when you go on reading the rest of the code, you are 100% confident that you don't have to keep in mind the meaning of result.
Kotlin have new features with NullPoint-Exception as Compare to Java.
Basically When we do Coding in Java , then we have to Check with !! in every Flied.
But in Kotlin, it is Easy way to Implement First
as Like,
Suppose, in Kotlin
var response:Json?=Null
response:Json?.let {
this part will handle automatic if response is Not Null....then this Block start Executing }?.run {
This is Nullable But, where we Can put Warring } So, I am Suggest you Guys to Start Work in Kotlin with this Features Provided by Kotlin.
(Flied)?.let { Not Null Value Comes Under }?.run{ Null Value Code }
This will Handle to NullPoint Exception or Protect You App for Crash
What you want to achieve
What you want to achieve is that the Kotlin compiler does a smart cast on the variable you are working with.
In all of your three examples, the compiler can do that.
Example:
if(myVar != null) {
foo(myVar) // smart cast: the compiler knows, that myVar can never be null here
}
The choice
Which one of the options to use, is really a matter of style. What you should not do is mix it up to often. Use one and stick to it.
You don't need to worry about performance since let and run are inlined (see inline function). This means that their code (body) is copied to the call site at compile time so there is no runtime overhead.

Is `a?.let{} ?: run{}` idiomatic in Kotlin?

I saw the following comment in a S.O. post, and I'm intrigued:
why don't you use if for null checks? a?.let{} ?: run{} is only appropriate in rare cases, otherwise it is not idiomatic – voddan May 15 '16 at 7:29 best way to null check in kotlin?
Why is that construct "only appropriate in rare cases"?
The lead engineer for Kotlin says,
run allows you to use multiple statements on the right side of an elvis operator https://stackoverflow.com/a/51241983/6656019
although I admit that's not actually endorsing it as idiomatic. Both of these posts seem to be from very well respected S.O. Kotlin contributors.
The post that inspired the original comment mentions that the let part of the expression is important if a is mutable. In that case, you'll need a?.let{} ?: run{} instead of if{} else {}.
I find I like the "let Elvis run" construct. Should I avoid it in most cases?
Thanks for any insight.
It's dangerous to conflate foo?.let { bar(it) } ?: baz() with if (foo != null) bar(foo) else baz().
Say you have a function: fun computeElements(): List<Int>? = emptyList()
Consider this code:
val maxElement = computeElements()?.let { it.max() } ?: return
println("Max element was $maxElement")
Compared to:
val list: List<Int>? = computeElements()
val maxElement = if (list != null) list.max() else return
println("Max element was $maxElement")
You may think these are two equivalent forms. However, if you run both, you'll see that the former does not print anything to stdout!
This is because it.max() returns null for an empty list (because there is no max element), which causes the right-hand side of the Elvis expression to be evaluated, and so the function returns early.
In short, ?.let { ... } ?: ... allows both branches of the "if-else" to be evaluated, which is dangerous. Aside from this form not being readable (if-else is universally understood, while let-run is not), subtle bugs can occur.
In that case, you'll need a?.let{} ?: run{} instead of if{} else {}
No, you can omit the run part of run { statement } and use a?.let{} ?: statement.
Should I avoid it in most cases?
You should use it when you need it. E.g. when you want to run multiple statements in that scenario. It is pointed out that that is a rare scenario. Often you will see just a single statement on the right hand side of an elvis operator.
And of course don't use it when you don't need it. Keep the code simple.

String values in Kotlin

In Java, if we do new String() we know it would create new string object and it would be different from the object created without 'new'(even if contents are same).
//Java
System.out.println("First" == new String("First")); // false always
In Kotlin, if I try to create String even by creating StringBuilder, it would still be identical to that created without String(..).
//Kotlin
println("First" == String(StringBuilder("First"))) //true always
If the created String(StringBuilder(..)) is going to reuse same string value, why give constructor? Does it do any value add, looking for such use-case.
Thanks.
By using the == operator you're checking structural equality between the strings (whether they represent the same sequence of characters). The Java equivalent of your Kotlin comparison code above would be something like this:
Object.equals("First", new String(new StringBuilder("First"))); // true
To check reference equality in Kotlin, you need to use the === operator.
Check out the Kotlin reference on Equality.
In Java when you use operator == you use referential equality. However, in Kotlin it is structural equality.
To use referential equality in Kotlin you need to use === operator.
You can check this doc page for more information: https://kotlinlang.org/docs/reference/equality.html
To use referential equality you need to use === operator in kotlin.
In java == operator use for referential equality. but in kotlin it is structural equality.
In Java, == is referential equality, but in Kotlin == is structural equality. That means, in Kotlin == and string1.equals(string2) both do the same thing. And in Kotlin we use === for referential equality.

OOP static variable changing value

I recently came upon this code in a comic, which I did not understand. Can someone please explain this to me? Is there any reason why the variable should change it's value?
static bool isCrazyMurderingRobot = false;
void interact_with_humans(void) {
if (isCrazyMurderingRobot = true)
kill(humans);
else
be_nice_to(humans)
}
Here is the comic: http://oppressive-silence.com/comics/oh-no-the-robots
The reason might be that in many programming languages,
checking for equality is done by using ==, while using a single = sign would assign the value to the variable).
So the code
if (isCrazyMurderingRobot = true)
would assign trueto the variable and the first condition will always be satisfied (as the result of the assignment would be true).
The correct line would be:
// use '==' here instead of '=' to check if variable is set
// using a single '=' would assign the value instead
if (isCrazyMurderingRobot == true)
For more details, please check these descriptions (they are for the C# language, but the operators behave similar in other languages like Java etc...)
assignment (=) operator.
equality (==) operator.