Я ОЧЕНЬ новичок в Scala, поэтому извинения, если что-то звучит немного основательно c. Работая над унифицированным заданием и не могу найти никаких похожих вопросов.
РЕДАКТИРОВАТЬ: Идея этой функции заключается в том, что я пропускаю строку данных и разделяю ее на отдельные элементы. Из того, что я могу сказать, вещи правильно разделены со списками, содержащими правильные типы данных и правильную информацию.
Итак, я создал функцию, которая возвращает Map [String, List [(Int, String, Float)]]
Функция выполняет другие функции, но для краткости, после того, как я построю список, вот как я строю карту и возвращаю ее: -
val newMap = Map(name -> newList2.toList)
newMap
Я могу newMap.foreach перебрать карту и найти все свои элементы. Это работает, как и ожидалось: -
(Sample Key,List((3,PlaceName1,2.7)))
(Sample Key,List((2,PlaceName1,3.8)))
(Sample Key,List((1,PlaceName1,0.75)))
Я просто пытаюсь вызвать эту функцию и сохранить карту в новую переменную. Я пробовал это двумя способами: -
val saveMap = separator("1:PlaceName1:0.75,2:PlaceName2:3.8,3:PlaceName3:2.7")
Однако, когда я пытаюсь циклически пройти через это, я получаю только первый элемент списка: -
(Sample Key,List((1,PlaceName1,0.75)))
Я также пытался использовать mapBuffer в формате: -
var mapBuffer: Map[String, List[(Int, String, Float)]] = Map()
mapBuffer = separator("1:PlaceName1:0.75,2:PlaceName2:3.8,3:PlaceName3:2.7")
Опять же, все, что я получу в ответ: -
mutated mapBuffer
(Sample Key,List((1,PlaceName1,0.75)))
Будучи новичком в Scala, но с некоторым опытом в Java и C#, это убивает меня, как я возвращаю значение карты, сохраняя его в значение карты, которое построено так же, и оно не проходит. Пробовал каждую итерацию карт и списков, которые я мог найти и не могу найти что-либо по этому вопросу при поиске.
Кто-нибудь может предложить какую-либо помощь?
РЕДАКТИРОВАТЬ:
Здесь весь код функции и как я пытаюсь ее вызвать.
def separator(data:String): Map[String, List[(Int, String, Float)]] = {
//Route name will be worked out later. For now, this is a sample.
val sampleRouteName = "First Route"
//Stage list will hold each list entry
val stageList = ListBuffer[(Int, String, Float)]()
//Stage list builder will put all the list entries together
var stageListBuilder = List[(Int, String, Float)]()
if (data.contains(",")) {
//Find index of first comma
val commaIndex = data.indexOf(",")
//Split everything before the comma off
val (firstEntry, restOfPhrase) = data.splitAt(commaIndex)
//Find the index of the colon in the first entry
val colonIndex = firstEntry.indexOf(":")
//Split everything before the colon off to just keep the number
val (number, restOfStage) = firstEntry.splitAt(colonIndex)
//Get rid of the first colon from the rest of the line
val restOfStage2 = restOfStage.replaceFirst(":", "")
//Find the index of the next colon
val colonIndex2 = restOfStage2.indexOf(":")
//Split everything before the colon off to just keep the stage name
val (stageName, restOfStage3) = restOfStage2.splitAt(colonIndex2)
//Get rid of the colon leaving just the stage length
val stageLength = restOfStage3.replaceFirst(":", "")
//Put all of these together into a list line in the builder
stageListBuilder = List((number.toInt,stageName,stageLength.toFloat))
//Add the list line from the builder to the list as an element
stageListBuilder.foreach(line => stageList += line)
//Call recursive function and remove the comma from the start
separator(restOfPhrase.replaceFirst(",", ""))
}
else if (data.length != 0) {
//Find index of first colon
val colonIndex = data.indexOf(":")
//Split everything before the colon off to just keep the number
val (number, restOfStage) = data.splitAt(colonIndex)
//Get rid of the first colon from the rest of the line
val restOfStage2 = restOfStage.replaceFirst(":", "")
//Find the index of the next colon
val colonIndex2 = restOfStage2.indexOf(":")
//Split everything before the colon off to just keep the stage name
val (stageName, restOfStage3) = restOfStage2.splitAt(colonIndex2)
//Get rid of the colon leaving just the stage length
val stageLength = restOfStage3.replaceFirst(":", "")
//Put all of these together into a list line in the builder
stageListBuilder = List((number.toInt,stageName,stageLength.toFloat))
//Add the list line from the builder to the list as an element
stageListBuilder.foreach(line => stageList += line)
}
//This is a map that accurately contains the key (ie. GCU Route) and a list of the routes.
val routeMap = Map(sampleRouteName -> stageList.toList)
//To test that the list has all the elements (CURRENTLY WORKING)
routeMap.foreach(line => println("TEST - " + line))
//Return the map
routeMap
}
//val saveMap = separator("1:City Chambers:0.75,2:Velodrome:3.8,3:People's Palace:2.7")
//Create new map buffer
var mapBuffer: Map[String, List[(Int, String, Float)]] = Map()
//Call separator function
mapBuffer = separator("1:City Chambers:0.75,2:Velodrome:3.8,3:People's Palace:2.7")
//Test that each element is in the list (CURRENTLY NOT WORKING)
mapBuffer.foreach(line => println(line))