报错:Operator '=='无法应用于'Byte'与'Type',求原因解析
报错原因分析:Operator '==' cannot be applied to 'Byte' and 'Type'
涉及代码
枚举类定义
enum class Type(val value: Byte){ TOP(0), BOTTOM(1); }
读取字节的变量
val position: Byte = binaryReader.readByte()
引发报错的判断代码
if (position == BarElement.Type.BOTTOM)
错误提示
Operator '==' cannot be applied to 'Byte' and 'Type'
报错原因
- 类型不匹配:
position是Byte类型的数值变量,而BarElement.Type.BOTTOM是Type枚举类的实例对象,两者属于完全不同的数据类型。 - Kotlin是强类型编程语言,编译器会严格校验类型匹配,不允许直接用
==比较不同类型的对象,防止出现逻辑错误。
修正示例
要判断字节值和枚举对应的数值是否相等,需要调用枚举实例的value属性获取对应的Byte值再比较:
if (position == BarElement.Type.BOTTOM.value)
内容的提问来源于stack exchange,提问作者NullPointerException
相关产品推荐
相关产品推荐

