①在函数作为参数传递时,入参逆变,返回值协变,Function1[-S, +T]。并不是说函数f的入参类型为A,可以传入其父类B,相反只能传入A及其子类。
②下面的例子中方法printBookList参数为一个函数info,函数info的入参为子类Book。而运行时传入的函数getTile入参为父类Publication,可以传入Publication及其子类,在方法printBookList调用info函数时,传入的正是其子类Book。而函数getTile作为参数传递时,其入参为要求的函数的父类,在类型参数上表现出逆变的特点。
object Customer{ def getTitle(p: Publication): String = p.title def main(args: Array[String]): Unit = { Library.printBookList(getTitle) } } class Publication(val title: String) class Book(title: String) extends Publication(title) object Library{ val books: Set[Book] = Set(new Book("Programming in Scala"), new Book("Walden")) def printBookList(info: Book => AnyRef) = { for (book <- books) println(info(book)) } }