考虑以下示例
abstract class Lookup(val code:String,val description:String)
class USState(code:String, description:String, val area:Symbol)
extends Lookup(code,description)
class Country(code:String, description:String, val postCode:String)
extends Lookup(code,description)
class HtmlLookupSelect(data:List[Lookup]) {
def render( valueMaker:(Lookup) => String ) =
data.map( (l) => valueMaker(l) )
}
val countries = List(
new Country("US","United States","USA"),
new Country("UK","Unites Kingdom","UK"),
new Country("CA","Canada","CAN"))
def lookupValue(l:Lookup) = l.description
def countryValue(c:Country) = c.description + "(" + c.postCode + ")"
val selector = new HtmlLookupSelect(countries) //Doesn't throw an error
selector.render(countryValue) //Throws an error
HtmlLookupSelect
需要一个 Lookup 对象列表作为构造函数参数。在创建 HtmlLookupSelect 对象时,会将一个县对象列表传递给它,并且编译器不会抛出错误,因为它会将其识别Country
为Lookup
但是在下一行中,当我尝试调用以 Country 作为参数类型(而不是预期的 Lookup)的方法时,我得到一个Type mismatch
错误。为什么会这样?