简体   繁体   English

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

[英]How to use conditional statements when overriding toString

I'm trying to override toString using conditional statements.我正在尝试使用条件语句覆盖 toString。 But I'm getting an error that says there is a type mismatch.但是我收到一个错误,指出类型不匹配。 It is supposed to be in String type and right now it's in Any type.它应该是 String 类型,现在它是 Any 类型。 noGoals, Tied are functions that returns true or false. 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"
}




    

The expression表达方式

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

defaults to默认为

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

where value () has Unit type, whilst values "aa" and "bb" have type String , and least upper bound of Unit and String is Any .其中 value ()具有Unit类型,而值"aa""bb"具有String类型,并且UnitString最小上限是Any Thus try providing default string to the last else branch like so因此尝试像这样向最后一个 else 分支提供默认字符串

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM