简体   繁体   中英

Scala - how to call a method which expects a Map

I have a scala method:

def commitSync(offsets: Map[TopicPartition, OffsetAndMetadata]) = {
   consumer.commitSync(offsets.asJava)
}

TopicPartition is a class with 2 parameters ( String and Int ):
TopicPartition(java.lang.String topic, int partition) .
Making it in scala like this:

val tp = new TopicPartition("sometopicname", 99)


OffsetAndMetadata is public kafka class with type 'long' in it:
OffsetAndMetadata​(long offset)

How to call now a method commitSync with these 2 parameters?

Thanks.

Lets say you declare two case classes

case class TopicPartition(str:String,intVal:Int)
case class OffsetAndMetadata(longVal:Long)

Now you create a map with these values

val offsets = Map(TopicPartition("sometopicname", 99) -> OffsetAndMetadata(999999))

You can now call your function commitSync as

commitSync(offsets)

I hope this answers your question.

Create a Map within the function call:

def commitSync(input: Map[String, Int]) = ??? // whatever

commitSync(Map("my string" -> 10))

Alternatively, you can define a Map as a val and pass it in as a parameter.

val map = Map("my string" -> 10)

commitSync(map)

Specifically with your example, something like this would work:

case class TopicPartition(val1: String, val2: Int)
case class OffsetAndMetadata(val1: Long)

def commitSync(input: Map[TopicPartition, OffsetAndMetadata]) = ??? // whatever

val map = Map(TopicPartition("string", 123) -> OffsetAndMetadata(1234567890))

commitSync(map)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM