2016-11-10 167 views
-2

我想創建一個搜索函數,所以用戶可以通過使用鍵值進行搜索,但是試圖使用的方法返回類型不匹配,已經取出不必要的代碼並顯示什麼是需要。我如何設定積分來接受一個I​​nt而不是「Any」?斯卡拉類型不匹配映射

「鍵入任何不符合類型爲int」

val mapdata = readFile("data.txt") 


    def handleTwo(): Boolean = { 
    mnuShowPointsForTeam(currentPointsForTeam) 
    true 
    } 




def mnuShowPointsForTeam(f: (String) => (String, Int)) = { 
    print("Team>") 
    val data = f(readLine) 
    println(s"${data._1}: ${data._2}") 
    } 



    def currentPointsForTeam(team: String): (String, Int) = { 
    val points = mapdata.get(team) match{ 
     case Some(p) => p 
     case None => 0 
    } 
    (team, points) 
    } 

的data.txt中

SK1, 9, 7, 2, 0, 7, 3, 7, 9, 1, 2, 8, 1, 9, 6, 5, 3, 2, 2, 7, 2, 8, 5, 4, 5, 1, 6, 5, 2, 4, 1 
SK2, 0, 7, 6, 3, 3, 3, 1, 6, 9, 2, 9, 7, 8, 7, 3, 6, 3, 5, 5, 2, 9, 7, 3, 4, 6, 3, 4, 3, 4, 1 
SK4, 2, 9, 5, 7, 0, 8, 6, 6, 7, 9, 0, 1, 3, 1, 6, 0, 0, 1, 3, 8, 5, 4, 0, 9, 7, 1, 4, 5, 2, 8 
SK5, 2, 6, 8, 0, 3, 5, 5, 2, 5, 9, 4, 5, 3, 5, 7, 8, 8, 2, 5, 9, 3, 8, 6, 7, 8, 7, 4, 1, 2, 3 
SK6, 2, 7, 5, 9, 1, 9, 8, 4, 1, 7, 3, 7, 0, 8, 4, 5, 9, 2, 4, 4, 8, 7, 9, 2, 2, 7, 9, 1, 6, 9 
SK7, 6, 9, 5, 0, 0, 0, 0, 5, 8, 3, 8, 7, 1, 9, 6, 1, 5, 3, 4, 7, 9, 5, 5, 9, 1, 4, 4, 0, 2, 0 
SK8, 2, 8, 8, 3, 1, 1, 0, 8, 5, 9, 0, 3, 1, 6, 8, 7, 9, 6, 7, 7, 0, 9, 5, 2, 5, 0, 2, 1, 8, 6 
SK9, 7, 1, 8, 8, 4, 4, 2, 2, 7, 4, 0, 6, 9, 5, 5, 4, 9, 1, 8, 6, 3, 4, 8, 2, 7, 9, 7, 2, 6, 6 
+0

mapData是什麼類型的? 「mnuShowPointsForTeam」的返回值是什麼(現在只是printlns)? – Thilo

+0

更新了這個問題,mapdata是一個外部txt文件,是的,它只是printlns團隊多數民衆贊成密鑰值輸入@Thilo –

+0

但是什麼是'mapData'類型?它是「Map [String,Any]」嗎?如果你不能創建'Map [String,Int]',那麼你必須在這個'case Some(p)'部分內部轉換/轉換爲Int。 – Thilo

回答

3

它看起來像你想返回一個元組與List[Int],而不僅僅是一個單一Int

如果是這樣

def currentPointsForTeam(team: String): (String, List[Int]) = 
    (team, mapdata.get(team).getOrElse(List.empty)) 
    // Or maybe List(0) instead of List.empty 

如果你想返回一個Int,你說如何從List[Int]走在映射到單一值。也許是一筆?

def currentPointsForTeam(team: String): (String, Int) = 
    (team, mapdata.get(team).map(_.sum).getOrElse(0)) 
+0

指甲的頭,這正是我想要實現的!謝謝 –

+0

第一個例子工作得很好,但第二個接受一個String Int而不是一個String List int,這將如何工作?只是測試它,我得到一個類型不匹配@Thilo –

+0

忽略最後的評論,在我想到之前鍵入!這就是現在的工作,再次感謝 –