Reputation: 7101
I have the followeing classes:
case class RolepermissionRow(roleid: Int, permissionid: Int)
and
case class RolePermissionJSON(
var id: Option[Long],
var num: Option[Int],
var name: Option[String],
var perms: Map[String, Boolean])
I create a map:
var s = Map("1" -> true)
I create a RolePermissionJSON:
val f = RolePermissionJSON(Some(0), Some(0), Some('test'), s)
And I would like to convert the perms Map to RolepermissionRow using the following code:
scala> f.perms.map { case (key, value) => if (value) RolepermissionRow(key.toInt, 1) }.toSeq
res7: Seq[Any] = List(RolepermissionRow(1,1))
The result is Seq[Any]
but I would like to have Seq[RolepermissionRow]
Upvotes: 1
Views: 57
Reputation: 14227
f.perms.filter(_._2).map{case (key, value) => RolepermissionRow(key.toInt, 1) }.toSeq
I think you should use filter
firstly to filter the map avoid empty Map
.
Upvotes: 1
Reputation: 6385
Simple changes required:
val z = f.perms.map { case (key, value) if (value) => RolepermissionRow(key.toInt, 1) }.toSeq
Now description:
In your code resulted Seq
contains of RolepermissionRow
s if value
is true
and Unit
s otherwise.
You should filter out "empty" elements of map that gives you Unit
.
UPD:
@nafg advice to use collect
to prevent match error in runtime.
Upvotes: 3