FrancMo
FrancMo

Reputation: 2679

From Java call Scala's Singleton object apply with trait

I have a pattern in scala like:

object ApiConnector {
 def apply(x: String): ApiConnector = new ApiConnectorImpl(x)
}

trait ApiConnector {
...
}

class ApiConnectorImpl extends ApiConnector {...}

when in Java code I want to use apply method like ApiConnector.apply("x") then I got an error:

Cannot access eu.xyz.api.ApiConnector

any ideas how to access this apply method from java code ?

Upvotes: 1

Views: 69

Answers (1)

Helix112
Helix112

Reputation: 306

Does this help ? This worked fine for me. ( Main.java and ApiConnector.scala are in the same folder )

Scala :

object ApiConnector {
  def apply(x: Any): ApiConnector = {
 new ApiConnectorImpl(x)
   }
}

trait ApiConnector {
 }

class ApiConnectorImpl(x : Any) extends ApiConnector {
    println("scala")
}

Java :

public class Main {
public static void main (String[] args) {
    System.out.println("from java ");
    ApiConnector$.MODULE$.apply("x");
}
}

In Java you only have to write : ApiConnector$.MODULE$.apply("x");

Upvotes: 1

Related Questions