我是斯卡拉新手,所以很可能這是一個非常明顯的錯誤。但是,我試圖將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