次の例を考えてみましょう
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 オブジェクトの作成中に、county オブジェクトのリストが渡されます。コンパイラは、オブジェクトCountry
のサブクラスとして認識されるため、エラーをスローしません。Lookup
しかし、次の行で、Country をパラメーターの型として (予期される Lookup ではなく) メソッドを呼び出そうとすると、Type mismatch
エラーが発生します。なぜこうなった?