2017-03-14 21 views
0

我試圖從我的函數中使用返回類型來取回對象或字符串。在它是一個對象的情況下,我想從這個對象開始調用方法。如果是字符串,我想在其他地方調用其他函數。我一直掛斷,因爲返回的東西不是我返回的對象,它是「左」類型的,我似乎無法將該對象從「左」類型中移回到「播放器」類型中我想要。這包含在擴展可變隊列的對象中。這裏是我的功能,查找基於關閉這是我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) 
+0

'solicitDecision'的返回類型是什麼?你期望從'currentPlayer.fold(...)'返回什麼? – danielnixon

+0

您無法將對象移出「Either」,因爲內部可能沒有對象。 – ziggystar

回答

2

你還沒有說你得到什麼錯誤,只是「這行不通」,並且已經發布的代碼是不夠完整的進行編譯和測試。當編譯器失敗時,currentPlayer類型是什麼?

話雖如此,你可能會考慮重構你的代碼。

def doMove = ActionQueue.popCurrentAction.fold(getDecision, stringStuff) 

def getDecision(player: Player) = .... 
def stringStuff(str: String) = .... 
+0

這是抱怨,因爲「solicitDecision不是任何[Player,String]的成員。」 currentPlayer的類型是[Player,String],solicitDecision是Player類中的一個方法。 – shutch

+1

啊,'.left'和'.right'方法並不是你想象的那樣。他們產生'Either'的左/右_projections_。他們不是提取器。爲此,你需要'currentAction.left.get',這是可行的,但可憐的斯卡拉風格。 – jwvh

2

製作案例區分和同時提取事物的最佳方法是使用模式匹配。

在你的情況,這將是大致如下代碼:

def doMove = { 
    val currentAction = ActionQueue.popCurrentAction 
    currentAction match { 
    case Left(currentPlayer) => 
     val playerDecision = currentPlayer.solicitDecision() 
     println(playerDecision) 
    case Right(string) => 
     println(string) 
    } 
} 

還請注意,我用val代替var。當你有一個你不打算改變的變量時,val是更好的樣式(粗略地說,它是一個只讀變量)。