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?

Jeffrey Chung
  • 19,319
  • 8
  • 34
  • 54
user1742188
  • 4,563
  • 8
  • 35
  • 60
  • Does this help? https://stackoverflow.com/questions/7819866/what-is-the-java-equivalent-of-a-scala-object – GhostCat Aug 18 '17 at 18:23

1 Answers1

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.

HTNW
  • 27,182
  • 1
  • 32
  • 60
  • Since the SimpleCredStashClient is also an object, should we use `SimpleCredStashClient.apply` or `SimpleCredStashClient$.apply`? – user1742188 Aug 18 '17 at 21:59
  • `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. – HTNW Aug 19 '17 at 01:55