https://kotlinlang.org logo
#getting-started
Title
# getting-started
m

MisileLab

08/05/2021, 12:39 AM
My Code
Copy code
fun changeIntToDouble(number: Int) {
    return number.toDouble()
}
but my ide said Type mismatch: inferred type is Int but Unit was expected How can I fix it?
r

Richard Gomez

08/05/2021, 12:42 AM
If you don't explicitly specify a return type it defaults to
Unit
, i.e. "nothing". You need to explicitly define it as:
Copy code
fun changeIntToDouble(number: Int): Double {
v

Vampire

08/05/2021, 12:48 AM
Or write it as expresssion body like
Copy code
fun changeIntToDouble(number: Int) = number.toDouble()
r

Richard Gomez

08/05/2021, 12:51 AM
^ That works too, although my understanding is that too many inferred return types can make IntelliJ slow.
5 Views