2012-02-27 2 views
1

나는 다음과 같은 방법이 가능 캐스트. 나는 무엇이 잘못되고 있는가?있습니다 스칼라

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

나는 다음과 같은 오류가 발생합니다 : 나는 ChildminderAccount 클래스에 generateTokenForAccount를 호출했다 value generateTokenForAccount is not a member of object com.bignibou.domain.ChildminderAccount 것처럼.

아무도 도와 줄 수 있습니까? (return처럼)

답변

10

당신 여기 캐스트를 사용하여 처리하는 더 나은 오류에 대한 '일치'를 사용할 수 있지만, 스칼라 asInstanceOf에서 일반적으로 코드 냄새입니다. 다음 대신보십시오 :

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

을 이제 당신이 ChildminderAccount에 넣어 경우가 ChildminderAccount을 얻을 것이다.

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

고맙습니다. 토마스! – balteo

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과 같습니다. 스칼라에서는 블록의 마지막 표현식이 자동으로 반환되므로 return 키워드를 제거 할 수도 있습니다.