我試圖從我的函數中使用返回類型來取回對象或字符串。在它是一個對象的情況下,我想從這個對象開始調用方法。如果是字符串,我想在其他地方調用其他函數。我一直掛斷,因爲返回的東西不是我返回的對象,它是「左」類型的,我似乎無法將該對象從「左」類型中移回到「播放器」類型中我想要。這包含在擴展可變隊列的對象中。這裏是我的功能,查找基於關閉這是我ActionQueue對象的關鍵在一個Map Player對象:解引用或者回到對象中
def popCurrentAction : Either[Player, String] = {
val currentAction = this.dequeue
this.enqueue(currentAction)
if (playerMap.get(currentAction) != None) {
Left((playerMap.get(currentAction).get))
}
else {
Right(currentAction)
}
}
這裏是我的功能,這是試圖使用它返回無論是「玩家」對象的函數或一個字符串。
def doMove = {
var currentAction = ActionQueue.popCurrentAction
if (currentAction.isLeft) {
var currentPlayer = currentAction.left
var playerDecision = currentPlayer.solicitDecision() // This doesn't work
println(playerDecision)
}
else {
// Do the stuff if what's returned is a string.
}
}
我已經使用.fold功能,這確實讓我打電話給solicitDecision功能和得到什麼返回試過,但我想直接使用Player對象。當然這是可能的。有人可以幫忙嗎?
var currentPlayer = currentAction
var playerDecision = currentPlayer.fold(_.solicitDecision(), _.toString())
// This is close but doesn't give me the object I'm trying to get!
println(playerDecision)
'solicitDecision'的返回類型是什麼?你期望從'currentPlayer.fold(...)'返回什麼? – danielnixon
您無法將對象移出「Either」,因爲內部可能沒有對象。 – ziggystar