Looks like you can use this script instead:
bin/kafka-topics.sh --zookeeper zk_host:port/chroot --alter --topic my_topic_name
--partitions 40
In the code it looks like they do same thing:
AdminUtils.createOrUpdateTopicPartitionAssignmentPathInZK(topic, partitionReplicaList, zkClient, true)
kafka-topics.sh
executes this piece of code as well as AddPartitionsCommand used by kafka-add-partition script.
However you have to be aware of re-partitioning when using key:
Be aware that one use case for partitions is to semantically partition
data, and adding partitions doesn’t change the partitioning of existing data so this may disturb consumers if they rely on that
partition. That is if data is partitioned byhash(key) % number_of_partitions
then this partitioning will potentially be
shuffled by adding partitions but Kafka will not attempt to
automatically redistribute data in any way.