Correct usage of return if in Kotlin [closed] - kotlin

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 days ago.
Improve this question
So in Kotlin you can write the below function in two ways:
fun getProduct(id: Int): Product? {
if (id < 1 ) return null
return productProvider.getProduct(id) /// Assuming getProduct NEVER fails
}
Or as below:
fun getProduct(id: Int) = if (id > 0 ){
productProvider.getProduct(id) /// Assuming getProduct NEVER fails
}else {
null
}
I am being suggested to always use the latter, as is the proper way.
Can someone point me in the right direction on this? Why is the second syntax better?
I can guess that performance wise they are exactly the same and ( IMO ) I do not find the second one more readable at all.

It is not more correct or better-performing. It is a style choice.
You do have the option of including the return type to make the second one more readable:
fun getProduct(id: Int): Product? = if (id > 0 ) {
productProvider.getProduct(id)
} else {
null
}
A when expression could also help here.

Related

Get random position from String based on condition [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I have one String variable like this:
var data = "FFFTTFFFT"
I want to get random position of 'T' present inside above String for which I am doing like this.
for (i in data.indices) {
if (data [i] == 'T') someList.add(i)
}
then
var randPos = someList.random()
I am able to do it using loop but I want to do it in idiomatic way in
Kotlin.
Shortest solution IMO:
val tIndices = data.mapIndexedNotNull { i, c -> i.takeIf { c == 'T' } }

Kotlin extract letters and keep only numbers in a String [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a string that is "M456456" for example, and i need to keep only the numbers. So the ouput has to be "456456"
How can i achieve this in Kotlin?
"M456456".filter(Char::isDigit)
"M456456".filter {it in '0'..'9'}
Use a regex replacement and remove all non digit characters:
val regex = """[^0-9]""".toRegex()
val input = "M456456"
val output = regex.replace(input, "")
println(output) // 456456

How to idiomatically format .apply{} in Kotlin? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
This might seem a little trivial, but since we read more code than we write, I want to know which of these versions looks nicer and more readable for you
private val VALUES by lazy {
mutableListOf<Value>().apply {
add(VALUE_1)
add(VALUE_2)
add(VALUE_3)
}
}
OR
private val VALUES by lazy {
mutableListOf<Value>()
.apply {
add(VALUE_1)
add(VALUE_2)
add(VALUE_3)
}
}
In other words, should we care that the method (.apply) be on the same line as the caller, or the ending curly bracket to be aligned with the (.apply) method?
As per https://kotlinlang.org/docs/reference/coding-conventions.html
Chained call wrapping
When wrapping chained calls, put the . character or the ?. operator on the next line, with a single indent:
val anchor = owner
?.firstChild!!
.siblings(forward = true)
.dropWhile { it is PsiComment || it is PsiWhiteSpace }
The first call in the chain usually should have a line break before it, but it's OK to omit it if the code makes more sense that way.
So it's up to you :)

Whats the best way to return a boolean from a function in VB.NET? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have two codes i am considering.
Which one would be the more correct way to return a boolean and why? I will be using this function in a MVC view.
Function MultiplicativeIsEffective(ByVal p As someobjectpassed) As Boolean
'1st:
Return Convert.ToBoolean(If(p.EffectiveDate > CDate("04/02/2015"), True, False))
'2nd:
Return policy.Endorsement.EffectiveDate > CDate("04/02/2015")
End Function
They are both correct in that they return the correct boolean value.
The first one just has redundancies in it.
p.EffectiveDate > CDate("04/02/2015")
results in a boolean value. The following does not add any value since all it does is look at a boolean value and then return that boolean value. So this is not doing anything.
If(p.EffectiveDate > CDate("04/02/2015"), True, False)
and finally the following is taking a boolean value and then converting it to a boolean value, which is actually not doing anything.
Convert.ToBoolean(If(p.EffectiveDate > CDate("04/02/2015"), True, False))
So the first one is doing a test that resulting in a boolean and then you twice convert that boolean into a boolean.
You want to use the second one.
They are both syntactically correct, but the bottom one is significantly more readable and avoids unnecessary work. The upper version converts a Boolean (p.EffectiveDate > CDate("04/02/2015")) to a Boolean (True or False in the If statement) to a Boolean (Convert.ToBoolean). The extra work is pointless.

Dynamic variable creation language [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Which computer languages will allow code that dynamically extracts a variable name from a string, like user types in an argument "hhh", and the code then knows to reference a variable with the identifier: hhh? Thanks for your help.
Not exactly "dynamic variable creation", but you can get pretty much the same effect by using an associative array (a.k.a. dictionary or map). For example, in Python:
vars = {}
vars['x'] = 'hello'
vars['y'] = 10
With the above code, the keys 'x' and 'y' in the dictionary are like dynamic variables for all practical purposes, for example:
print vars['x']
> hello
vars['y'] + 6
> 16
As a matter of fact, under the hood many programming languages (Python, JavaScript, etc.) use a dictionary of bindings for implementing variables and scoping rules.
The associative array is probably a better idea to use, but just in case, php supports this without putting the code inside an eval function:
<?php
class ff {
var $u = "aagg";
}
$y = new ff();
$i = "u";
echo $y->$i;
?>