Search code examples
javaclojureopentoktokbox

Translate Java method invocation chaining and object construction to normal Clojure


What is the Clojure equivalent of chaining method invocation in Java?

TokenOptions tokenOpts = new TokenOptions.Builder()
      .role(Role.MODERATOR)
      .expireTime((System.currentTimeMillis() / 1000) + (7 * 24 * 60 * 60)) // in one week
      .data(connectionMetadata)
      .build());

This code was copied from https://tokbox.com/opentok/tutorials/create-token/java/


Solution

  • Step one: move the opening paren one token to the left, add a doto to chain the method application:

    (def tokenOpts (doto (TokenOptions/Builder)
                         (.role Role.MODERATOR)
                         (.expireTime (System.currentTimeMillis() / 1000) + (7 * 24 * 60 * 60)) // in one week
                         (.data connectionMetadata)
                         (.build));
    

    Then "recur" on the arguments to each method:

    (def tokenOpts (doto (TokenOptions/Builder)
                         (.role Role/MODERATOR)
                         (.expireTime (+ (System.currentTimeMillis() / 1000) 
                                      (7 * 24 * 60 * 60)) // in one week
                         (.data connectionMetadata)
                         (.build));
    

    Then "recur" to the arguments to those functions (note that I switched to the word function here, as we are out of Java mode-of-thinking at this point:

    (def tokenOpts (doto (TokenOptions/Builder)
                         (.role Role/MODERATOR)
                         (.expireTime (+ (/ (System/currentTimeMillis) 1000) 
                                         (* 7 24 60 60))) ;; in one week
                         (.data connectionMetadata)
                         (.build))
    

    You will need to add a (:import .....) to your namespace declaration (the block at the top of the file) to make sure you have Roll and TokenOptions classes available under those names.