2013-11-04 18 views
0

我的工作斯卡拉名單列表轉換爲自定義對象「點」轉換列表,以流的列表 - 函數式編程

class Point(val x: Int, val y: Int) { 
    var cX: Int = x 
    var cY: Int = y 
    } 

我應該使用的foreach或我應該使用地圖或的foreach在這個名單案例

def list_To_Point(_listOfPoints :List[List[String]]) : List[Point] = { 

    var elem = 
    lazy val _list: List[Point] = _listOfPoints.map(p=> new Point(p[0],p[1]) 
     _list 
    } 

我無法弄清楚問題到底在哪裏?

+0

爲什麼不使用元組作爲內部結構? –

+0

我不認爲我需要這個,因爲他們都是同名的。我需要知道每次如何推送列表中的新對象 – DataT

回答

1

醜陋的地獄和未經考驗的,但它應該工作(請考慮對你的結構是不變的):

case class Point(x:Int,y:Int) 




object Point { 


    def listToPoint(listOfPoints:List[List[String]]):List[Point] = 
    listOfPoints.map(p => new Point(p(0).toInt,p(1).toInt)) 
} 
4
def listToPoint(l:List[List[String]]):List[Point] = 
    l.collect({case x::y::Nil => new Point(x.toInt,y.toInt)}) 

但你真的不應該使用一個列表[字符串]代表什麼,基本上(Int,Int) ...