Search code examples
clojure

Clojure , how to pass correct param into function


I'm newbee in Clojure world. My pet project is writing of kafka consumer / producer. There a lot of topic in www ,but I've faced with misunderstanding.

There is a code

(ns producer
  (:require [clojure.tools.logging :as log])
  (:import  (java.util Properties)
            (org.apache.kafka.common.serialization StringSerializer)
            (org.apache.kafka.clients.producer KafkaProducer ProducerRecord))
  (:gen-class))

(defn create-kafka-producer [server]
    (let [producer-props {
        "value.serializer" StringSerializer
        "key.serializer" StringSerializer
        "bootstrap.servers" server }]

        (KafkaProducer. producer-props)))

(defn send-single-message [producer topic-name record]
    (.send producer (ProducerRecord. topic-name (str "Value: " (.value record)))))

(defn -main []
    (def svr "localhost:8084")
    (def producer (create-kafka-producer svr))
    (send-single-message producer "Test msg"))

I want just pass some msg into kafka through send-single-message function. But as you see in code example is using (.value record) and when I'm trying to pass the "Test msg" string it crashed and show the followed error

Exception in thread "main" java.lang.IllegalArgumentException: No matching field found: value for class java.lang.String

I understand that is because I've pass string object, that has no .value So, how is it possible to solve that issue? Thanks in advance p.s. I've tried to pass other structure, but no results or different errors


Solution

  • As you noted, the error is because you're attempting to get the value field of the passed object, but you're passing in a String which doesn't have a value field.

    Checking that ProducerRecord constructor signature, it takes a generic argument of type V (which is just an Object as far as Clojure is concerned). I'd just pass the String directly and omit the value field access.