Kotlin代码乘法操作编译报错,寻求原因及解决方法
单位转换代码编译失败原因排查
我是Kotlin初学者,参考Android官方Codelab示例编写的单位转换代码无法编译,但示例代码可正常运行。相关代码及错误信息如下:
代码:
package com.example.converterapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.example.converterapp.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.calculateButton.setOnClickListener{ calculate() } } fun calculate() { val stringInTextField = binding.measurementToConvert.text.toString() val measurement = stringInTextField.toDoubleOrNull() if (measurement == null) { binding.convertedMeasurement.text = "" return } val selectedId = binding.conversionOptions.checkedRadioButtonId val conversion = when (selectedId) { R.id.oz_to_cups -> 0.125 R.id.cups_to_oz -> 8 R.id.oz_to_grams -> 28.3495 else -> 0.035274 } var desiredMeasurement = measurement * conversion val roundUp = binding.roundUpSwitch.isChecked if (roundUp) { desiredMeasurement = kotlin.math.ceil(desiredMeasurement) } binding.convertedMeasurement.text = getString(R.string.convertedMeasurement, desiredMeasurement) } }
错误信息:
\ConverterApp\app\src\main\java\com\example\converterapp\MainActivity.kt: (33, 46): None of the following functions can be called with the arguments supplied: public final operator fun times(other: Byte): Double defined in kotlin.Double public final operator fun times(other: Double): Double defined in kotlin.Double public final operator fun times(other: Float): Double defined in kotlin.Double public final operator fun times(other: Int): Double defined in kotlin.Double public final operator fun times(other: Long): Double defined in kotlin.Double public final operator fun times(other: Short): Double defined in kotlin.Double
原因分析:
编译错误出现在measurement * conversion这一行。问题在于conversion变量的类型推断:when表达式中,R.id.cups_to_oz -> 8返回的是Int类型,而其他分支返回的是Double类型。Kotlin会把conversion的类型推断为Number(所有数值类型的父类),但Double的times方法(即乘法运算符)不接受Number类型的参数,因此触发编译错误。
解决方法:
把when表达式中所有分支的数值统一改为Double类型,确保conversion被推断为Double。只需要把8改成8.0即可:
val conversion = when (selectedId) { R.id.oz_to_cups -> 0.125 R.id.cups_to_oz -> 8.0 // 改为Double类型 R.id.oz_to_grams -> 28.3495 else -> 0.035274 }
修改后,conversion的类型会被正确推断为Double,就能和measurement(Double类型)正常执行乘法运算了。
内容的提问来源于stack exchange,提问作者Moya.A
相关产品推荐
相关产品推荐

