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

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.

Related

Kotlin Unsafe and Safe cast operator

why we need Unsafe and Safe cast operators while only the Safe cast operator is enough to keep things simple?
"Unsafe" cast operator
val x: String = y as String
If y is null, the code above throws an exception. To make such code correct for null values, use the nullable type on the right-hand side of the cast:
val x: String? = y as String?
"Safe" (nullable) cast operator
To avoid exceptions, use the safe cast operator as? that returns null on failure
val x: String? = y as? String
You do not need to cast String to String. That cast does not make sense.
You just have to use
val x: String?
if you want to make the string variable nullable or you just use
val x: String
that is not nullable. Also, consider using val and var to be able to assign new value to your variable.
It's a good practice to avoid nullability as much as possible. As you can see, the safe cast always returns a nullable value.
But you should use the unsafe cast carefully - only when you are sure about the type. Another use-case of the unsafe cast is when you want to cast some value to it's supertype.

What is the difference between nullabe and non-nullable type in Kotlin

Please explain the difference between nullable and non-nullable type. I am new to kotlin and i am confused. Thanks
Nullable types can hold nulls. When type is nullable the question mark is set after it's type:
val str: String? = null
Non-nullable types can't hold nulls:
val str: String = "some value"
If we try to set null value to Non-nullable type, IDE will give an error and code will not be compiled:
val str: String = null // error, the code won't compile
Here you can read more about Null Safety.
when a variable has a nullable type then the variable can have value or it can also have value null and the program will not force close like most java based programs with null pointer exeption error messages.
for example :
val data: DataResponse? = null
its more save then you use val data: String because when your data variabel dont have value or null when you use it your program not force close at that time.
you can use your data variabel like this:
your_text.text = data
and your code will not force close.
but if your code like this, it means nonNullable.
val data: DataResponse
your apps will force close at that time you use your variabel

Kotlin: null and "Overload resolution ambiguity"

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.

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.

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.