gpt4 book ai didi

scala - 覆盖 toString 时如何使用条件语句

转载 作者:行者123 更新时间:2023-12-01 23:46:28 25 4
gpt4 key购买 nike

我正在尝试使用条件语句覆盖 toString。但是我收到一条错误消息,指出存在类型不匹配。它应该是 String 类型,现在它是 Any 类型。noGoals、Tied 是返回 true 或 false 的函数。

override def toString = {
if (this.noGoals)
s"${this.home} vs. ${this.away} at ${this.location}: no goals"
else if (this.Tied)
s"${this.home} vs. ${this.away} at ${this.location}: tied"
}





最佳答案

表达式

if (conditionA) "aa"
else if (conditionB) "bb"

默认为

if (conditionA) "aa"        
else if (conditionB) "bb"
else () // oops () types to Unit

其中值 () 具有 Unit 类型,而值 "aa""bb" 具有类型StringUnitString的最小上界是Any。因此尝试像这样向最后一个 else 分支提供默认字符串

if (conditionA) "aa"
else if (conditionB) "bb"
else "default"

关于scala - 覆盖 toString 时如何使用条件语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64070288/

25 4 0
文章推荐: css - VueJS - 使用 v-html 添加 css 样式
文章推荐: Java 正则表达式转义序列
文章推荐: java - 将 ArrayList 作为参数传递给方法,处理 arrayList 并返回它 - Java