我是斯卡拉新手,所以很可能这是一个非常明显的错误。但是,我试图将List [Object]转换为List [A],其中A是类中的参数。斯卡拉地图方法不像预期的那样行事
class AbstractHibernateDAO[A<:Serializable]{
def findAll: List[A] = {
val objList = currentSession.createQuery("from " + clazz.getName()).list()
objList.map{_.asInstanceOf[A]}
}
}
Eclipse是呕吐了起来:
type mismatch; found : ?0(in method findAll) => A where type ?0(in method findAll) required: (some other)?0(in method findAll) => ? where type (some other)?0(in method findAll) AbstractHibernateDAO.scala /springHibernateNoXML/src/main/scala/my/package
我也试着长期形成
objList.map{obj => obj.asInstanceOf[A]}
,并得到同样的结果。
任何人都可以帮我一把吗?
[编辑 - 信息]
对于那些要求,这里的完整清单:
package name.me
import java.io.Serializable
import java.util.List
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.config.BeanDefinition
import org.springframework.context.annotation.Scope
import org.springframework.orm.hibernate3.HibernateTemplate
import org.springframework.stereotype.Repository
import com.google.common.base.Preconditions
import org.hibernate.SessionFactory
import org.hibernate.Session
import collection.JavaConversions._
@Repository
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
class AbstractHibernateDAO[A<:Serializable]{
val clazz: Class[A] = null
@Autowired val sessionFactory: SessionFactory = null
def currentSession: Session = {
sessionFactory getCurrentSession
}
def findOne(id: Long): A = {
Preconditions checkArgument(id != null)
currentSession.get(clazz, id).asInstanceOf[A]
}
def findAll: List[A] = {
val objList = currentSession.createQuery("from " + clazz.getName()).list()
objList.map(_.asInstanceOf[A])
//This works
//objList.asInstanceOf[List[A]]
}
def save(entity:A){
Preconditions checkNotNull entity
currentSession persist entity
}
def update(entity: A){
Preconditions checkNotNull entity
currentSession merge entity
}
def delete(entity: A){
Preconditions checkNotNull entity
currentSession delete entity
}
def deleteById(entityId: Long){
Preconditions checkNotNull entityId
val entity = findOne(entityId)
Preconditions checkNotNull entity
delete(entity)
}
}
凡'clazz'定义? – 2012-04-22 17:05:31