4

I'm trying to create a scala object, kafka.utils.ZKStringSerializer in clojure. (It's in org.apache.kafka/kafka_2.10 "0.8.0")

Since I know little about scala, I don't know how to call its constructor. I tried like this:

(import 'kafka.utils.ZKStringSerializer)
(ZKStringSerializer.)                      
; or (new ZKStringSerializer)

And got an error: CompilerException java.lang.IllegalArgumentException: No matching ctor found for class kafka.utils.ZKStringSerializer

I tried using (clojure.reflect/reflect ZKStringSerializer) to see its methods but there are only some static methods. And (class ZKStringSerializer) tells me it is a class, not an instance I want.

The object is implemented like this:

object ZKStringSerializer extends ZkSerializer {

  @throws(classOf[ZkMarshallingError])
  def serialize(data : Object) : Array[Byte] = data.asInstanceOf[String].getBytes("UTF-8")

  @throws(classOf[ZkMarshallingError])
  def deserialize(bytes : Array[Byte]) : Object = {
    if (bytes == null)
      null
    else
      new String(bytes, "UTF-8")
  }
}
halfelf
  • 9,737
  • 13
  • 54
  • 63

1 Answers1

11

All scala objects are singletons in terms of java. There is no public constructor. You should use static field MODULE$ to get an instance of singleton.

I don't know clojure, but according to this page it looks like you should use this:

ZKStringSerializer$/MODULE$

Note also that the actual type name of object contains $ as last character.

senia
  • 37,745
  • 4
  • 88
  • 129
  • It works! Thanks a lot! I didn't know the `$` notation before. – halfelf Jan 24 '14 at 09:11
  • @halfelf: take a look at companion object: `class Test; object Test`. An instance of singleton should have a class, but class name `Test` is already in use. Manual usage of `$` is deprecated in scala: all synthetic term names contains `$`. – senia Jan 24 '14 at 09:19
  • @halfelf: actually not all synthetic term names contains `$`, only methods you should not use manually. – senia Jan 24 '14 at 09:50
  • hmm.. looks like [that page](http://clojure.org/java_interop#Java%20Interop-Classname/staticField) no longer references `MODULE$`. fwiw, i'm wondering how to access a scala object from clojure. – ari gold Sep 10 '21 at 20:29
  • 1
    @arigold that page describes accessing java static fields. Scala creates java static field `MODULE$` for singleton objects. – senia Sep 12 '21 at 13:02
  • ah i see, thanks.. it was an indirect reference. – ari gold Sep 21 '21 at 00:45