When the input data format is not correct, there will be a outofindex error in Activitydata, but more often we only care about the desired results and do not want to know what the error, and then write such a code
def
parseCSV(csv
:
String)
=
{
try
{
Some {
csv.split(
"\n"
).map { line
=
>
val
tokens
=
line.split(
";"
)
ActivityData(tokens(
0
).toLong, tokens(
1
).toInt, tokens(
2
).toInt, tokens(
3
).toLong)
}
}
}
catch
{
case
_
:
Throwable
=
> None
}
}
And after import Scala.util.Try, we can write this code.
def
parseCSV(csv
:
String)
=
Try {
csv.split(
"\n"
).map { line
=
>
val
tokens
=
line.split(
";"
)
ActivityData(tokens(
0
).toLong, tokens(
1
).toInt, tokens(
2
).toInt, tokens(
3
).toLong)
}
}
Like option, Try has two possibilities of success and fail, and the usage and option type
parseCSV(csvdata).map { entries
=
>
//do something with the data
}.getOrElse {
BadRequest(
"Invalid CSV Data"
)
//this is Play Framework specific (returns a 400 HTTP response with a message)
}
The reason we can do this is that Try is monad, and when everything is normal, it returns Success (something) and returns Failure (error) when it fails
Scala try Monad