2012-02-27 176 views
1

我有以下方法蒙上成爲可能。我錯了什麼?在斯卡拉

@Transactional 
    def registerChildminderAccount(childminderAccount: ChildminderAccount): Boolean = { 
    childminderAccountDAO.save((ChildminderAccount) generateTokenForAccount(childminderAccount))//problem here!! 
    if (mailerService.requestChildminderConfirmation(childminderAccount)) { 
     return true 
    } else { 
     return false 
    } 
    } 

我得到以下錯誤:value generateTokenForAccount is not a member of object com.bignibou.domain.ChildminderAccount我彷彿是調用的是ChildminderAccount類generateTokenForAccount。

任何人都可以請幫忙嗎?

回答

10

可以這裏使用強制,但一般在斯卡拉asInstanceOf是一個代碼味道(因爲是return)。而不是嘗試以下操作:

def generateTokenForAccount[A <: Account](account: A): A = { 
    account.setAccountToken(UUID.randomUUID.toString) 
    account 
} 

現在,如果你把一個ChildminderAccount你會得到了ChildminderAccount

4
generateTokenForAccount(childminderAccount).asInstanceOf[ChildminderAccount] 
+0

非常感謝Tomasz! – balteo 2012-02-27 23:04:57

4

可能需要使用「匹配」更好的錯誤處理

generateTokenForAccount(childminderAccount) match { 
    case acc: ChildminderAccount => childminderAccountDAO.save(acc) 
    case _ => // ERROR 
} 
0

爲什麼generateTokenForAccount會返回其輸入?這是具有欺騙性的,因爲它會讓你相信它構造了一個新的,修改過的對象,但事實上它並沒有;相反,它發生變異,從傳遞的對象應該返回Unit以表明這一點:

def generateTokenForAccount(account: Account) { 
    account.setAccountToken(UUID.randomUUID().toString()) 
} 

現在式引導你看到,你可以簡單地使用序列的影響:

def registerChildminderAccount(childminderAccount: ChildminderAccount): Boolean = { 
    generateTokenForAccount(childminderAccount) 
    childminderAccountDAO.save(childminderAccount) 
    mailerService.requestChildminderConfirmation(childminderAccount) 
    } 

而且,只要你有if foo { return true } else { return false },這相當於return foo。在Scala中,塊中的最後一個表達式會自動返回,因此您甚至可以刪除return關鍵字。