11

Is there an implicit method to convert scala.collection.mutable.StringBuilder to java.lang.StringBuilder?

I am using a Java library (JCommander) in which one of the methods (usage) takes a java.jang.StringBuilder argument.

3 Answers 3

10

You can't start with a Scala StringBuilder and then obtain the Java version. You can, however, wrap a java.lang.StringBuilder in the Scala version. So:

val jsb = new java.lang.StringBuilder();
val sb = new StringBuilder(jsb);
// Do Scala-y stuff with sb
JCommander.whatever.usage(jsb);
// Do more Scala-y stuff

Since--not a guarantee, but true in practice right now (2.8, 2.9)--the Scala wrapper doesn't store any state (instead just referring to the Java version), you're safe to mix and match usage of the two.

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

Comments

4

Looking at the source code, it seems there's absolutely no way to get a java.lang.StringBuilder from a scala.collection.mutable.StringBuilder.

You can create a new java.lang.StringBuilder with Scala's, going through a conversion of some type (String or CharSequence).

Comments

1

Use this implicit transform do do this:

    implicit def b2b(b: scala.collection.mutable.StringBuilder) = 
        new java.lang.StringBuilder(b)

1 Comment

Actually, I don't think that will work. I presume that any Java method that expects a java.lang.StringBuilder expects to modify it and allow the caller access to those changes. The implicit method you show creates a "defensive" copy of the scala.collection.mutable.StringBuilder. Any changes in the called method will not be reflected in the scala.collection.mutable.StringBuilder. Now that I think about it, the only way it could be implemented is if scala.collection.mutable.StringBuilder extended or wrapped java.lang.StringBuilder.

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.