Scala: Read file from IO and line by line match it construct a case class and add the case class to a List -
i have been trying learn scala in free time , learn write code in more functional manner; anyways have hit problem trying write (what thought) simple tool reading formatted name data out of file , creating list of data containing case classes... not work however:
object namedatautil { /** * reads data file containing formatted name data list containing case classes. * * @param filename name of file (with extension) read data from. * @return list of case classes containing data specified file. */ def readinfile(filename: string): list[namedatum] = { val names: list[namedatum] = source.fromurl(getclass.getresource("/"+filename)).getlines() foreach { line => line.trim.split("\\s+") match { case array(name,freq,cumfreq,rank) => namedatum(name, freq.todouble, cumfreq.todouble, rank.toint) } } names } }
any appreciated. thanks!
replace foreach
map
, you'll iterator[namedatum]
. add tolist
after getlines()
list[namedatum]
instead, though it's better use tostream
, work stream[namedatum]
instead, if expect file big fit in memory.
Comments
Post a Comment