Kotlin: null and "Overload resolution ambiguity" - kotlin

I want to call a overloaded java-function from Kotlin. I want to use a null for parameter that significant to a overload resolution.
How to specify IntArray type for null value?
I don't like a solution with additional varibale of common type.

Instead of a variable just cast it, i.e. null as IntArray?, e.g.:
origImg.data.getSamples(0, 0, origImg.width, origImg.height, 0, null as IntArray?)
Note that this is the same behaviour as in Java, where you also needed to cast null, e.g. (int[]) null, to call the appropriate overloaded method.
You could build a function that gives you a ~typed null (if it doesn't exist yet) with a reified type:
inline fun <reified T>typedNull(): T? = null
and calling it with:
typedNull<IntArray>()
But then again, null as IntArray? is clear enough I think and people know it already.

Related

How to safe-cast a null into a generic type <T>?

I want to know if there's a way to make a safe cast from null, the next example throws an UNCHECKED CAST warning:
fun <T> notInitialized(): T = null as T
So, If anyone has an idea of how to make a safe cast from this function please let me know!
You can do fun <T> notInitialized(): T? = null - you need to return a nullable type (otherwise your cast is explicitly unsafe), and since you're already specifying the return type you don't need to cast null as T?. Or you could do that and skip the return type, fun <T> notInitialized() = null as T?
Either way you're just returning null, which isn't any specific type - you're just telling the caller to treat it as one. And that type needs to be nullable
As an alternative to the generic answer (which is the usual way to approach these things), you could do this:
fun notInitialised(): Nothing? = null
Nothing is the ‘bottom’ type, which has no values and is the subset of all other types. So Nothing? is a type with just one value (null), and is a subtype of all nullable types. This means you can assign it to any nullable type without needing any type inference, e.g.:
val a: Int? = notInitialised()
But I still don't understand the purpose of this — it doesn't seem to have any benefit over just using null directly. If you're using null to represent an uninitialised value (as opposed to an unknown value, a missing value, an inapplicable value, an unavailable value, an undefined value, an unchanged value, a secret value, or any of the other subtly-different things that people use null to mean), then that should be spelled out in the property/method/variable's doc comment — in which case there's no point spelling it out again in the code.

how to write unit test for isNullOrEmpty() function

I have a function for validating the request, it can't be null or empty, I can test if the end point is empty, but I can't pass the value as null to the request in test, I will get "NulllPointerException", how can I test null case?
fun validateRequest(request: RegisteRequest) {
validateEndPoint(request.EendPoint)
}
private fun validateEndPoint(endPoint: String) {
if (endPoint.isNullOrEmpty()) {
logger.error("Request is missing EndPoint")
throw IllegalArgumentException(ERROR_MESSAGE_MISSING_END_POINT)
}
}
Kotlin's type system is able to differentiate between values that can be null (e.g., String?) and values that can't be null (e.g., String). You can find more details here.
In your case you're defining a function that takes in input a non-null String, so if you're invoking it from Kotlin, the Kotlin compiler will make sure you don't pass a null value – it'll fail the build if you try to do so.
If somehow you still manage to pass a null value (e.g., via reflection or by invoking the function from Java), you'll get a NullPointerException (as documented here), because the Kotlin compiler will actually insert some instructions under the hood to make sure you don't provide a null value.
So if your code is meant to be called from Java or if you really want to test what happens if you pass null, you'll have to assert that a NullPointerException is thrown.
If, instead, null is a valid value and you want to handle it differently, you'll have to change the signature of your method so that it accepts a null parameter (note the type of the parameter here is String?):
private fun validateEndPoint(endPoint: String?) {
...
}

Why do optionals in Kotlin require explicit initialisation?

When defining an optional property in a class, Kotlin requires that it is explicitly initialised as null, like so:
var myString: String? = null
Is there any reason that the compiler cannot infer this initial value? I believe Swift would let you skip the = null part, however this is a compiler error in Kotlin. Wouldn't it be simpler to automatically have the value null after writing the following?
var myString: String?
Explicitness is a part of the overall language design in Kotlin. There are no implicit defaults for any types in Kotlin language. There is also desire to discourage (mis)use of nulls, so in respect to initialization nulls are not considered special in any way. If you have a non-nullable string var myString: String they you are required to initialize it with something just like you are required to initialize a nullable string var myString: String? with something, so this way its initial value is always explicit.
Note, technically speaking, String? in Kotlin is not an optional string in Kotlin. In Kotlin it is called a nullable string. However, the most common use-case for nulls is to represent the "absence of value".
There is no reason null must be the initial value of uninitialized variables.
It is not inference.
It is just a rule in Swift, and Kotlin does not have such rule.
Which do you think var a: Int? should be initialized as? 0 or null? Both arguments may have some reasons.
And in Kotlin, nullables are not optionals.

Kotlin function with unspecified return type

In Kotlin how do you declare a function with an unspecified return type? For example, if I have a function that is to return a list of integers, but in the case of null input it should return just null, instead of a List.
How do I declare a function that could either return a MutableList or a null?
You just have to declare your type as nullable by using the ? at the end of the type declaration.
For example, this function takes a non-null Boolean and returns either a MutableList of Int or a null:
fun maybeGetList(input: Boolean): MutableList<Int>? =
if (input) mutableListOf(1) else null
Kotlin has quite extensive documentation on the subject.
Todd gave an good answer based on what you asked for, but if you are using Kotlin then it might be better to learn to use it properly.
Using null should be avoided as much as possible, that is why Kotlin even has null-safe types so it forces you to rethink your code and try to write it without nasty ?, just look at that sign, it is like it asks you do you really want to do this.
Now in your case you even have 2 great options for avoiding null and writing more idiomatic Kotlin:
Return empty list:
fun getList(condition: Boolean): List<Int>
= if(condition) listOf(1,2,3) else emptyList()
fun getMutableList(condition: Boolean): MutableList<Int>
= if(condition) mutableListOf(1,2,3) else mutableListOf()
Use Optional from Java:
fun getOptionalList(condition: Boolean): Optional<List<Int>>
= if (condition) Optional.of(listOf(1, 2, 3)) else Optional.empty()
You might think that doing this adds complexity but its quite the opposite, using null adds much more complexity because when you return it you must handle that null on every place you call this method, this way you encapsulate dangerous state instead of spreading it.

What is the Kotlin double-bang (!!) operator?

I'm converting Java to Kotlin with Android Studio. I get double bang after the instance variable. What is the double bang and more importantly where is this documented?
mMap!!.addMarker(MarkerOptions().position(london).title("Marker in London"))
This is unsafe nullable type (T?) conversion to a non-nullable type (T),
!! will throw NullPointerException if the value is null.
It is documented here along with Kotlin means of null-safety.
Here is an example to make things clearer.
Say you have this function
fun main(args: Array<String>) {
var email: String
email = null
println(email)
}
This will produce the following compilation error.
Null can not be a value of a non-null type String
Now you can prevent that by adding a question mark to the String type to make it nullable.
So we have
fun main(args: Array<String>) {
var email: String?
email = null
println(email)
}
This produces a result of
null
Now if we want the function to throw an exception when the value of email is null, we can add two exclamations at the end of email. Like this
fun main(args: Array<String>) {
var email: String?
email = null
println(email!!)
}
This will throw a KotlinNullPointerException
Not-null assertion operator
Kotlin's double-bang operator is an excellent sample for fans of NullPointerException (NPE).
The not-null assertion operator !! converts any value to a non-null type and throws an exception if the value is null.
val nonNull = str!!.length
If you write str!!, it'll return a non-null value of str (str is a String? here) or throw an NPE if str is null. This operator should be used in cases where the developer is guaranteeing – the value will never be null. If you want an NPE, you have to ask for it explicitly.
!!(Double Bang) operator is an operator to assert forcibly nullable variable as not null.
Example:
Here str is a string with value. But its nullable. Since its nullable we need to handle null for avoid compile time exceptions.
val str :String? = "Foo"
val lowerCase = str!!.lowerCase()
Here if we add !! operator, since it has non null value it would work and lowercased value will be assigned.
val str :String? = "Foo"
str = null
val lowerCase = str!!.lowerCase()
But here if you assign null value and use the particular value , it will throw KotlinNullPointerException.
One important thing here is, in most of the cases one should avoid as !! operator unless if its 100% sure that value is non null value or if the exception is caught and handled properly.
If you need to avoid this NPE, you can use null safe operators with elvis operators. null safe call ?. opertators with elvis are better way to handle null safety in kotlin.
You can read more about Kotlin null safety here
!! is an assertion that it is not null. Two exclamation marks after a nullable value convert it to a non-nullable type. At the same time, before the conversion, it is not checked in any way that the value really does not contain null. Therefore, if during the execution of the program it turns out that the value that the !! operator is trying to convert is still null, then there will be only one way out - to throw a NullPointerException.
Java
throws NullPointerException
Kotlin
simply use !!
This would help for understanding
It means in human language: I promise I will assign value later, but please don't worry for now my variable. On the other it is non-null variable terminologically.