在kotlin中,在超载功能时,我不断获得“类型不匹配”。在一些非常基本的代码上
在底部功能上,我继续得到
类型不匹配:推断类型是INT,但预期的double
我以前通过将输出声明为带有INT输入的双输出来完成。但是,这是我第一次使用“ Math.pi”和“ Math.pow”
fun main(args: Array<String>) {
val radius = 13;
println(getArea(radius));
}
fun getArea(radius: Double): Double{
val area = Math.pow(radius, radius) * Math.PI;
return area;
}
fun getArea(radius: Int): Double{
val area = Math.pow(radius, radius) * Math.PI;
return area;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将尝试总结不同的贡献评论,以为您的问题做出希望的完整答案。
不兼容的类型
首先是您实际问题。
Math.pow
函数具有以下签名。汇编错误:
与以前可能使用的其他某些语言相比,kotlin不执行数字类型的自动类型铸造,您可以找到更多信息,为什么会在此中找到更多信息” https://stackoverflow.com/q/44081233/3160089"> stackoverflow上的问题。
数学公式中的错误
假设您的目标是计算一个圆的面积,则在公式中有一个错误。
它应该是
a = r^2 *π
,但是您得到了a = r^r *π
。代码重复使用
如果要为不同的键入参数提供相同的功能,则可以提供一次实现它并使用过载版本中的单个实现。
保持靠近原始代码,这可能看起来像以下内容。
语法改进
kotlin是一种非常表现力的语言,它使您可以按照以下方式简化代码。您不需要Kotlin的分号。对于单个表达式的简单函数,Kotlin提供了。 Kotlin的标准库还提供了基本的数学功能,例如A 和a Math 。
I'll try to summarize the different contributed comments to formulate a hopefully complete answer to your question.
Incompatible type
First and foremost to your actual problem. the
Math.pow
function has the following signature, as can be seen in the documentation:You however attempt to invoke this function by passing two
Int
egers into it, thus you receive the compilation error:In contrast to some other languages one might have worked with before, Kotlin does not perform automatic type-casting for numeric types, you can find more information why that is in this question on StackOverflow.
Mistake in math formula
Assuming you aim to calculate the area of a circle, you have a mistake in your formula.
It should be
A = r^2 * π
but you gotA = r^r * π
.Code reuse
If you want to provide the same function for differently typed parameters it might provide useful to implement it once and make use of the single implementation in the overloaded versions.
Keeping close to your original code, this might look something like the following.
Syntax improvements
Kotlin is a very expressive language, which allows you to simplify your code as follows. You do not need semicolons in Kotlin. For simple functions that are a single expression, Kotlin provides a neat shortened syntax. The standard library of Kotlin also provides basic math functionality such as a pow function and a π constant. So you don't need to rely on the Java/JVM specific functions, e.g. from
Math
.