Consider the following example
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
expects a list of Lookup objects as constructor parameter. While creating a HtmlLookupSelect object, a list of county objects are passed to it and the compiler doesn't throw an error since it recognizes Country
as a subclass of Lookup
But in the next line, when I try to invoke a method with Country as the parameter type(instead of the expected Lookup), I get a Type mismatch
error. Why is this happening?