Scala代码类型不匹配错误:Found Unit,Required Storage
Scala类型不匹配错误:Unit vs Storage
你的代码:
var storage: Storage = if (config.storageType == StorageType.MAP) MapStorage() else if (config.storageType == StorageType.LIST) ListStorage() else ()
收到的错误:
[E007] Type Mismatch Error
Found: Unit
Required: ****.utils.Storage
错误原因
Scala里的if-else是表达式,要求所有分支返回兼容的类型。你前两个分支返回的是Storage的子类(MapStorage、ListStorage),但最后else ()返回的是Unit类型(Scala中()就是Unit的实例),和Storage类型完全不兼容,因此编译器抛出类型不匹配错误。
解决方案
方案1:用模式匹配(推荐,更符合Scala风格)
模式匹配能更清晰处理枚举分支,若枚举新增值,开启编译警告后还能提示你补全分支:
var storage: Storage = config.storageType match { case StorageType.MAP => MapStorage() case StorageType.LIST => ListStorage() // 处理未覆盖的枚举值,比如抛出异常或返回默认实现 case _ => throw new IllegalArgumentException(s"不支持的存储类型: ${config.storageType}") }
方案2:补全else分支的合法返回值
如果需要保留if-else结构,确保else分支返回Storage类型的实例:
var storage: Storage = if (config.storageType == StorageType.MAP) MapStorage() else if (config.storageType == StorageType.LIST) ListStorage() else { // 可选:返回默认存储实现,或者抛出异常 // DefaultStorage() throw new IllegalArgumentException(s"未知存储类型: ${config.storageType}") }
额外建议
如果后续不需要重新赋值storage,尽量用val替代var,更符合Scala函数式编程的设计理念。
内容的提问来源于stack exchange,提问作者Simran Munot
相关产品推荐
相关产品推荐

