0

I have an object in Scala that returns a Set[String]:

object MyObject {
  val setOfStrings = Set[String]("string1","string2")
}

I can successfully refer to that val from my Python code (using Py4J) with this:

jvm.com.package.MyObject.setOfStrings()

however I can't figure out how to do anything useful with it. I want to convert it into a python set.

I managed to do it using this:

eval(
  str(
    jvm.com.package.MyObject.setOfStrings()
  )
      .replace("Set(", "{\"")
      .replace(")", "\"}")
      .replace(", ", "\", \"")
)

but that's a horrifically brittle way of achieving it and I'm assuming Py4J provides a much better way.

I'm aware that SetConverter can convert a python set to a Java set, but I want to do the opposite. Anyone know how?

jamiet
  • 10,501
  • 14
  • 80
  • 159

1 Answers1

1

You could use a java.util.Set on the Scala side, which will be converted by Py4J into the Python equivalent MutableSet.

If you don't want to use Java collections in your Scala code base, then you might want to convert a scala.collection.immutable.Set into its Java equivalent when you want to communicate with Python.

I didn't run this code, but you could probably do this:

object YourObject {
  val setOfStrings = Set[String]("string1","string2")
}

object ViewObject {
  import scala.jdk.CollectionConverters._
  def setOfStrings: java.util.Set[String] = YourObject.setOfStrings.asJava
}

and use it in Python:

jvm.com.package.ViewObject.setOfStrings()

Note that in this case, you won't be able to modify the collection. If you want to be able to update the view in Python and have the changes reflected back in Scala, then you'll have to use a scala.collection.mutable.Set in your Scala code.

ljleb
  • 182
  • 1
  • 14