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")
  }
}

1 Answer 1

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.

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

5 Comments

It works! Thanks a lot! I didn't know the $ notation before.
@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 $.
@halfelf: actually not all synthetic term names contains $, only methods you should not use manually.
hmm.. looks like that page no longer references MODULE$. fwiw, i'm wondering how to access a scala object from clojure.
@arigold that page describes accessing java static fields. Scala creates java static field MODULE$ for singleton objects.

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.