scala中是否可以使用强制转换

时间:2012-02-27 22:58:17

标签: scala casting operators

我有以下方法:

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

我传递给这个方法一个Account的子类,即ChildminderAccount,我试图在scala中转换结果无济于事。我错了什么?

@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一样。

有人可以帮忙吗?

4 个答案:

答案 0 :(得分:10)

可以在这里使用强制转型,但一般来说,Scala asInstanceOf是一种代码气味(就像return一样)。请尝试以下方法:

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

现在,如果你输入ChildminderAccount,你就可以获得ChildminderAccount

答案 1 :(得分:4)

generateTokenForAccount(childminderAccount).asInstanceOf[ChildminderAccount]

答案 2 :(得分:4)

可能希望使用'匹配'来更好地处理错误

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

答案 3 :(得分: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关键字。

相关问题