title: Scala - Return value from Callbacks
body: <p>I am fairly new to scala programming. Can someone please help me with return value from callbacks. How could I return a callback value as JsObject from the calling method? I am using the Play2 framework with an actor system. Please let me know if my return type is wrong and I should return Future as compared to JsObject in SendToKafka method.</p>
  
  <p>I have the following code </p>
  
  <pre class="lang-scala prettyprint-override"><code>override def SendToKafka(data: JsValue): Option[JsObject] = {
    val props: Map[String, AnyRef] = Map(
      "bootstrap.servers" -&gt; "localhost:9092",
      "group.id" -&gt; "CountryCounter",
      "key.serializer" -&gt; "io.confluent.kafka.serializers.KafkaAvroSerializer",
      "value.serializer" -&gt; "io.confluent.kafka.serializers.KafkaAvroSerializer",
      "schema.registry.url" -&gt; "http://localhost:8081"
    )
  
    val schema: Schema = new Parser().parse(Source.fromURL(getClass.getResource("/test.avsc")).mkString)
  
    val gRecord: GenericRecord = new GenericData.Record(schema)
    gRecord.put("emp_id", request.emp_id)
  
    val producer = new KafkaProducer[Int, GenericRecord](props.asJava)
    val record = new ProducerRecord("Emp", 1, gRecord)
  
    val promise = Promise[RecordMetadata]()
  
    producer.send(record, producerCallback(promise))
    val f = promise.future
    val returnValue : Some[JsObject] =null
    val con = Future {
      f onComplete {
        case Success(r) =&gt; accessLogger.info("r" + r.offset())
        case Failure(e) =&gt; accessLogger.info("e "+ e)
      }
  
      // I would like to return offset as JsObject or exception ( if any )
    }
  
    private def producerCallback(promise: Promise[RecordMetadata]): Callback = {
      new Callback {
        override def onCompletion(metadata: RecordMetadata, exception: Exception): Unit = {
  
        val result = if (exception == null) {
          //accessLogger.info("offset - " + metadata.offset())
          // I would like to return this offset as JsObject 
          Success(metadata)
        }
        else {
          accessLogger.error(exception.printStackTrace().toString)
          Failure(exception)
          // I would like to return exception (if any ) as JsObject 
        }
        promise.complete(result)
      }
    }
  }
  </code></pre>