如何在Scala中将函数中的对象作为参数传递?

时间:2011-08-11 23:15:33

标签: scala types mongodb

给出两个扩展类的对象:

object PageDAO
  extends SalatDAO[Page, Long](collection=Config.getMongoDB("db_development")("pages"))

object BookDAO
  extends SalatDAO[Book, Long](collection=Config.getMongoDB("db_development")("books"))

我想编写一个将对象作为参数的函数:

def find[ID](salatDAO:SalatDAO[Product,ID]) = salatDAO.find(MongoDBObject()).limit(10)

scala> find[Long](PageDAO)
<console>:27: error: type mismatch;
 found   : PageDAO.type (with underlying type object PageDAO)
 required: com.novus.salat.dao.SalatDAO[Product,Long]
Note: Page <: Product (and PageDAO.type <: com.novus.salat.dao.SalatDAO[Page,Long]), but class SalatDAO is invariant in type ObjectType.
You may wish to define ObjectType as +ObjectType instead. (SLS 4.5)
       find[Long](PageDAO)

这可能吗?

1 个答案:

答案 0 :(得分:3)

只需遵循编译器的建议即可。如果您希望SalatDAO[A, _]SalatDAO[B, _]时成为A <: B的子类(即AB的子类时),请声明SalatDAO在第一个参数中是协变

trait SalatDAO[+A, B] // ...
               ^       <-- that plus does the trick

如果您无法更改方差注释,则可以使用注释中提出的Eastsun使用的站点边界,即Java;

def find[P <: Product, I](salatDAO: SalatDAO[P,I]) = // ...