0

I use Scala in my project and want to integrate with Stripe, but it provides only Java API. For example, to create session I use:

val params = new util.HashMap[String, AnyRef]
val paymentMethodTypes = new util.ArrayList[String]
paymentMethodTypes.add("card")
params.put("payment_method_types", paymentMethodTypes)
params.put("mode", "setup")
params.put("success_url", "https://test.app/success")
params.put("cancel_url", "https://test.app/cancel")
val session = Session.create(params)

This code works perfectly, but it's very ugly and contains a lot of boilerplate. I'd like to use a Scala Map[String, AnyRef] and create session as follows:

import scala.collection.JavaConverters._
val params2: Map[String, AnyRef] = Map(
  "payment_method_types" -> List("card"),
  "mode" -> "setup",
  "success_url" -> "https://test.app/success",
  "cancel_url" -> "https://test.app/cancel"
)
val session2 = Session.create(mapAsJavaMap[String, AnyRef](params2))

It turns out that mapAsJavaMap can't convert nested objects in the Map. Is there a way to convert arbitrary Scala Map with other Maps and Lists inside to their Java equivalents?

1
  • What version of scala? What error do you get? Commented Sep 20, 2019 at 2:46

2 Answers 2

3

JavaConverters has been deprecated. Try CollectionConverters.

import scala.jdk.CollectionConverters._

def convertMap[K](scalaMap :Map[K,AnyRef]) :java.util.Map[K,AnyRef] =
  scalaMap.map{ case (k,v) => v match {
    case m:Map[_,AnyRef] => (k, convertMap(m))  //recursive
    case l:List[_]       => (k, l.asJava)       //java.util.List[_]
    case _               => (k, v)              //unchanged
  }}.asJava

Not sure if this will actually work for you, what with all the values being type AnyRef. Try it and see what happens.

Sign up to request clarification or add additional context in comments.

1 Comment

I get non-variable type argument AnyRef in type pattern scala.collection.immutable.Map[_,AnyRef] (the underlying of Map[_,AnyRef]) is unchecked since it is eliminated by erasure
2

You can use JavaConverters and here is an example how you can convert collections recursively.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.