0

I am trying to use a Scala class that has a default argument:

object SimpleCredStashClient {

  def apply(kms: AWSKMSClient, dynamo: AmazonDynamoDBClient, aes: AESEncryption = DefaultAESEncryption) 
  ...
}

When I try to instantiate an instance of this class from Java, I get the error:

Error:(489, 43) java: cannot find symbol
  symbol:   method SimpleCredStashClient(com.amazonaws.services.kms.AWSKMSClient,com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient)
  location: class com.engineersgate.build.util.CredentialsUtil

DefaultAESEncryption is a Scala object. How do I access the Scala object in Java?

1

1 Answer 1

1

Default arguments become synthetic methods of the form <meth>$default$<idx>(). Further, instances of an object A may be found at A$.MODULE$ (if A is a top-level object), or at outer.A() (if A is defined as something like class O { object A }).Therefore, there are two ways to do this:

Direct usage of object:

SimpleCredStashClient.apply(
    kms,
    dynamo,
    DefaultAESEncryption$.MODULE$
);

Default argument:

SimpleCredStashClient.apply(
    kms,
    dynamo,
    SimpleCredStashClient.apply$default$3()
);

The first one certainly looks better, but if the default argument ever changes, you'll have to update this code too. In the second one, the argument is whatever the default argument is, and will only break if the argument stops having a default, or changes its index. Scala uses the second method when compiled.

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

2 Comments

Since the SimpleCredStashClient is also an object, should we use SimpleCredStashClient.apply or SimpleCredStashClient$.apply?
SimpleCredStashClient.apply is a static method generated by scalac for the sole purpose of Java interop, so you should use that. It simply forwards to SimpleCredStashClient$.MODULE$.apply, which is what Scala code ends up using.

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.