user1742188
user1742188

Reputation: 5083

Accessing a Scala object from Java code

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?

Upvotes: 0

Views: 556

Answers (1)

HTNW
HTNW

Reputation: 29193

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.

Upvotes: 1

Related Questions