Hi!
I’m a beginner in Kotlin programming and I’m trying to understand how the “if” function works.
Following is a code I’m trying to fix, some suggestion and explanation from you?
fun sumNumbers(num1: Double, num2: Double): Double{
if(num1 || num2 is Int){
num1.toInt()
num2.toInt()
}
return num1 + num2
}
fun main(args:Array<String>) {
var somma = sumNumbers(5, 34)
print(somma)
}
}
if is not a function, it is a keyword that executes its block only if the condition inside of it is true.
This will never work cuz 1) you can’t have 2 conditions in one using ||, so it’ll need to be if(num1 is Int || num2 is Int) 2) This is an ||, but it seems as though you actually want a && because you are converting both numbers and finally 3) a Double can never be cast as an Int, because they are totally different types. To be honest, I don’t really see the purpose of that function. Did you maybe just want to add 2 Ints? if so, then make num1 and num2 Ints. Could you please clarify what you are trying to achieve?
Here’s an example for a function summing two numbers:
fun sumNumbers(num1: Double, num2: Double): Double = num1 + num2
fun main() {
val sum = sumNumbers(5.0, 34.0)
println(sum)
}
Just as a reminder, when we say Integer and Double, we aren’t talking about numbers like we do learning math–instead we’re talking about types. It’s reasonable to say whole numbers and integers are a subset of rational numbers. An Int in programming is not a subtype of Double.
Checking if an Double is an Int is not checking if it’s a whole number. You might as well check if a Double is a File or String
import java.io.File
fun main() {
//sampleStart
5.0 is File
5.0 is String
5.0 is Int
//sampleEnd
}
If what you really want is to check if a Double is a whole number, you can do that a few different ways. Here’s an example using compareTo:
fun isWholeNumber(num: Double): Boolean {
return num.compareTo(num.toInt()) == 0
}
fun main() {
val wholeDouble = 5.0
println(isWholeNumber(wholeDouble))
val nonWholeDouble = 5.0000001
println(isWholeNumber(nonWholeDouble))
}
// The return type must be the same as param type. Anything can be used for the T type.
fun <T> exampleGenericFunction(param: T): T {
return TODO("Return some type of T")
}