I think this is a pretty basic question, but I just want to clarify. If I have a variable with a null value, and pass it as a parameter that is optional, will the parameter get the null value, or the default value?
dim str As String = "foo"
dim obj As Object
//call 1
Request(str, str)
//call 2
Request(str)
//call 3
Request(str, obj)
public Function Request(byVal someVal As String, Optional ByVal someVal2 As String = "bar")
...
I know that call 1 will make someval == someval2 == "foo" inside the function, and call 2 will make someval == "foo" and someval2 == "bar" and call 3 will make someval == foo but what is someval2 equal to in call 3? nullable or bar?
Also - I'm relatively new to vb.net and I don't think I fully understand the null/nullable/nothing concept differences from C#
"what is someval2 equal to in call 3? nullable or bar?" It will be null.
Well, actually, you can't do call 3 ... it will not compile because you can't pass an object as a string parameter. However, if you had dim obj as string = null, then it would be null.
If no parameter value is supplied to an optional parameter, the default value for that parameter will be used.
If Nothing is passed to an optional parameter, the parameter value will be Nothing and the default value will be ignored.
Related
I have an instance which can be null. Fox example
var str: String? = null
So I need to check if str is String. Do I need to check for null if I use the is operator.
First option:
if(str is String) {}
Second option:
if(str != null && str is String) {}
Please help me which way is better to use ?
The is operator is safe and returns false in the case you supply a null instance
https://pl.kotl.in/HIECwc4Av
Somewhere, you HAVE to nullcheck.
Kotlin provides many ways to enforce non-null:
Use a non-null type:
var nonNull : String = ""
var nullable : String? = "" // notice the ?
nullable = null // works fine!
nonNull = null // compiler error
and if you encounter a nullable type, you can use let {} ?: run {} construct to unwrap it and execute your code with a non-nullable:
nullable?.let { // use "it" to access the now non-null value
print(it)
} ?: run { // else
print("I am null! Big Sad!")
}
Kotlin strictly distinguishes between nullable T? and nonnull T.
Use T wherever possible to avoid null checks.
I'm trying to code this problem: Initialise a String as “Hello, Kotlin” and change its value to null. Now print the length of the String using safe call and non-null assertion operator.
I know how to initialise a string with null value, but don't know how to set it as null after it's been already initialised with a different string value.
To set null in a variable it needs to be declared as nullbable.
fun main() {
var srt: String? = "Hello, Kotlin"
println(srt)
srt = null
println(srt)
}
I want to fully understand the different between compareTo and equals.
I have used this code while trying to understand the difference between them:
println("${'A'.compareTo('b')}")
println("${'A'.equals('b')}")
While using compareTo I get -1 as a result. Nothing is wrong here.
It is also mentioned in the documentation that I will get -1 as a result if the strings are not the same:
Compares this object with the specified object for order. Returns zero if this object is equal to the specified other object, a negative number if it's less than other, or a positive number if it's greater than other.
And while using equals the result that I got was false, then again it looks good as the documentation mentioned - this method will return a boolean:
Indicates whether some other object is "equal to" this one.
Maybe I am missing something really simple, but in the described case, what is the difference between those methods (other than the value that is coming from compareTo and equals)?
The difference between equals and compareTo comes from a few sources.
First, equals is inherited from the Any type in Kotlin, so it is a method attached to all values in the language.
compareTo is inherited from the Comparable type, specifically meaning only its inheritors of:
Boolean, Byte, Char, Double, Duration, Enum, Float, Int etc...
will have the method.
Second, the signature of returned value is different.
Equals has a return of Boolean, meaning you only have true or false being returned from the method call. This will only tell you directly if they are the same or not, with no extra information
The compareTo method has a return of Int, which is a magnitude of the difference between the comparison of the input type. The comparison can not be between different types.
The return of a positive Integer that the Receiver value, is greater than the input value being checked against
To clarify, the Receiver is the variable or instance that the compareTo method is being called on.
For example:
val myValue: Boolean = false
val myCheck: Boolean = true
myValue.compareTo(myCheck) // Return: 1
In that code, the Receiver would be myValue because it is calling the method compareTo. Kotlin interprets true to be a greater value than false so myValue.compareTo(myCheck) will return1`
The return of 0 means that the Receiver value is the same value as the input parameter value.
val myValue: Boolean = true
val otherValue: Boolean = true
myValue.compareTo(otherValue) // Return: 0
The return of a negative number is a magnitude of difference between the two values, specific to each type based on the Receiver value being considered a value of less than the input parameter.
val myString = "zza"
val otherString = "zzz"
myString.compareTo(otherString) // Return: -25
The equality being a bit complicated to explain, but being the same length with only 1 Char place being different, it returns the difference of the Char values as an Int.
val myString = "zz"
val otherString = "zzz"
myString.compareTo(otherString) // Return: -1
In this case the difference is literally the existence of 1 Char, and does not have a value difference to assign.
For equals, the comparative other can be of Any type, not specifically the same type as the Receiver like in compareTo.
The equals method is also an operator function and can be syntactically used such as:
val myString: String = "Hello World"
val otherString: String = "Hello World"
myString == otherString // Return: true
Any non-null value can not be equal to null:
val myString = "Hello World"
val maybeNull: String? = null
myString == maybeNull // Return: false
Equality is specific to each type and has it's own specific documentation to clarify its nuances: Kotlin Equality
I am starting with Kotlin and trying to understand something.
var foo: String = null does not compile as expected.
var foo: String? = null should be the correct syntax and compile as expected.
So why does var foo = null compile??
The type of foo in this case will be inferred to Nothing?, which is a very special type. In short, Nothing is a type that is a subtype of every type in Kotlin (therefore Nothing? is a subtype of every nullable type), has no instances, and can be used as a return type for functions that can never return.
Even though Nothing can have no instances, null itself of type Nothing?, which is why it can be assigned to any nullable variable.
You can learn more in depth about Nothing in the official docs, in this excellent Medium article, and in this article that covers the overall Kotlin type hierarchy.
For var foo = null, the type is inferred to Nothing?, and is therefore valid syntax.
var foo = null is equivalent to var foo:Nothing? = null
similarly
var foo = "" is equivalent to var foo:String = ""
and slo
var foo = 1 is equivalent to var foo:Int = 1
The compiler is smart enough to infer the type of foo from the right hand expression type.
My understanding of the Integer.TryParse() function was that it tried to parse an integer from the passed in string and if the parse failed the result integer would remain as it did before.
I have an integer with a default value of -1 which I would like to remain at -1 if the parse fails. However the Integer.TryParse() function on failing to parse is changing this default value to zero.
Dim defaultValue As Integer = -1
Dim parseSuccess As Boolean = Integer.TryParse("", defaultValue)
Debug.Print("defaultValue {0}", defaultValue)
Debug.Print("parseSuccess {0}", parseSuccess)
My expectation is that the code snippet above should output:
defaultValue -1
parseSuccess False
However instead it outputs:
defaultValue 0
parseSuccess False
Is my understanding correct?
It's an out parameter, which means it must be set by the method (unless it throws an exception) - the method can't see what the original value was.
The alternative would have been to make it a ref parameter and only set it on success, but that would mean forcing callers to initialize the variable first even if they didn't want this behaviour.
You can write your own utility method though:
public bool TryParseInt32(string text, ref int value)
{
int tmp;
if (int.TryParse(text, out tmp))
{
value = tmp;
return true;
}
else
{
return false; // Leave "value" as it was
}
}
You are correct, TryParse uses 0 if it fails. (MSDN says this quite clearly)
But you could check paseSuccess and return your default value if this is what you want to.