首页 > 解决方案 > 在 Kotlin 中,在函数中返回双精度时我不应该使用“return”吗?

问题描述

我可以构建应用程序,但我意识到我缺乏一些 Kotlin 知识。我注册了codewars,第一个问题如下:

找出为什么代码不起作用...

fun multiply(x: double, y: double) => x * y

我的答案

fun multiply(x: double, y: double) => Double {
return x * y
}

标签: kotlin

解决方案


没有像doubleKotlin 中那样的 keywork。Kotlin 对 double 类型使用 Class 类型实现(在 JVM 中它仍然使用原始 double 类型)

您可以按如下方式定义函数:

fun multiply(x: Double, y: Double): Double { return x * y }

或者如果您希望使用单语句方法,那么您可以定义如下

fun multiply(x: Double, y: Double) = x * y


推荐阅读