1

now my code like this:

val elems  = List("1","2","3")
for(elem <- elems){
  redis.sadd("elems",elem)
}

is there any method to sadd multiple elements like python's api.

How to use sadd with multiple elements in Redis using Python API?

I use https://github.com/debasishg/scala-redis

Community
  • 1
  • 1
Fr4ndy
  • 13
  • 2

1 Answers1

4

Looking through sources you can see that sadd is defined here https://github.com/debasishg/scala-redis/blob/master/src/main/scala/com/redis/SetOperations.scala as:

def sadd(key: Any, value: Any, values: Any*)(implicit format: Format): Option[Long] =
    send("SADD", List(key, value) ::: values.toList)(asLong)

This is good if you list elements manually i.e.

redis.sadd("elems", "1", "2", "3")

It is done to disallow using empty list. What you can do with this api is

val elems  = List("1","2","3")
redis.sadd("elems", elems.head, elems.tail: _*)

you could as well add a method that suits you to RedisClient class via implicit conversion

implicit class RichRedis(self: RedisClient) {
    def saddseq(key: Any, values: Seq[Any])(implicit format: Format): Option[Long] =
        self.sadd(key, values.head, values.tail: _*)
}

and then you could do:

val elems  = List("1","2","3")
redis.saddseq("elems", elems)

Note that you can't overload sadd it needs a different name.

Remember that you cannot call head on an empty list, so whenever you use this method with empty list you will get exception, which is reasonable considering that you can't add just a key.

Łukasz
  • 8,555
  • 2
  • 28
  • 51
  • I think you switched `sadd`/`saddseq` in you implicit class. It could also be worth mentioning that it'll raise an exception when `values` is empty. – Marth Nov 25 '15 at 09:03
  • Right I switched them, thank you. This will rise an exception, yes but I think this is what should happen. I think you can't add just a key without values, this is why original method prevented it. With workaround like this I think exception should be expected. – Łukasz Nov 25 '15 at 09:08
  • 1
    Yes, I don't think think there is any reasonable behavior here apart from throwing a exception. Just thought a `obviously, this will raise … so you might to handle that earlier in your code` mention might be useful. – Marth Nov 25 '15 at 09:11