• # Conversion automatique de code

    Posté par (site web personnel, Mastodon) . En réponse au journal Kotaten : un Tap Tempo en Kotlin. Évalué à 4.

    À noter que Kotlin (enfin, au moins IntelliJ) permet de convertir du code Java en Kotlin. Ça fonctionne, mais nécessite un peu de nettoyage et de « Kotlinisation » du code.

    Par exemple, si je convertis le TapTempo Java directement, j'obtiens (après avoir remis les fonctions directement dans le fichier, sans passer par un objet inutile) :

    package com.i2bp.taptempo
    import org.apache.commons.cli.CommandLine
    import org.apache.commons.cli.CommandLineParser
    import org.apache.commons.cli.DefaultParser
    import org.apache.commons.cli.HelpFormatter
    import org.apache.commons.cli.Option
    import org.apache.commons.cli.Options
    import org.apache.commons.cli.ParseException
    import java.text.DecimalFormat
    import java.util.Scanner
    import java.util.ArrayDeque
    import java.util.Date
    import java.util.Deque
    fun computeBPM(currentTime: Long, lastTime: Long, occurenceCount: Int): Double {
     var occurenceCount = occurenceCount
     if (occurenceCount == 0) {
     occurenceCount = 1
     }
     val elapsedTime = (currentTime - lastTime).toDouble()
     val meanTime = elapsedTime / occurenceCount
     return 60.0 * 1000 / meanTime
    }
    fun main(args: Array<String>) {
     var precision = 0
     var resetTime = 5
     var sampleSize = 5
     val options = Options()
     val hitTimePoints = ArrayDeque<Long>()
     val optHelp = Option("h", "help", false, "Display this help message.")
     optHelp.isRequired = false
     options.addOption(optHelp)
     val optPrecision = Option("p", "precision", true, "Set the decimal precision of the tempo display. Default is 0 digits, max is 5 digits.")
     optPrecision.isRequired = false
     options.addOption(optPrecision)
     val optResetTime = Option("r", "reset-time", true, "Set the time in second to reset the computation. Default is 5 seconds.")
     optResetTime.isRequired = false
     options.addOption(optResetTime)
     val optSampleSize = Option("s", "sample-size", true, "Set the number of samples needed to compute the tempo. Default is 5 samples.")
     optSampleSize.isRequired = false
     options.addOption(optSampleSize)
     val optVersion = Option("v", "version", false, "Display the version.")
     optVersion.isRequired = false
     options.addOption(optVersion)
     val parser = DefaultParser()
     val formatter = HelpFormatter()
     var cmd: CommandLine? = null
     try {
     cmd = parser.parse(options, args)
     if (cmd!!.hasOption('p')) {
     precision = Integer.parseInt(cmd.getOptionValue('p'))
     if (precision < 0) {
     precision = 0
     } else if (precision > 5) {
     precision = 5
     }
     }
     if (cmd.hasOption('r')) {
     resetTime = Integer.parseInt(cmd.getOptionValue('r'))
     if (resetTime < 1) {
     resetTime = 1
     }
     }
     if (cmd.hasOption('s')) {
     sampleSize = Integer.parseInt(cmd.getOptionValue('s'))
     if (sampleSize < 1) {
     sampleSize = 1
     }
     }
     } catch (e: ParseException) {
     println(e.javaClass.toString() + ": " + e.message)
     formatter.printHelp("TempoTap", options)
     System.exit(1)
     } catch (e: NumberFormatException) {
     println(e.javaClass.toString() + ": " + e.message)
     formatter.printHelp("TempoTap", options)
     System.exit(1)
     }
     if (cmd!!.hasOption('h') || cmd.hasOption('v')) {
     if (cmd.hasOption('h')) {
     formatter.printHelp("TempoTap", options)
     }
     if (cmd.hasOption('v')) {
     println("Version: 1.0")
     }
     System.exit(0)
     }
     val df = DecimalFormat()
     df.maximumFractionDigits = precision
     df.minimumFractionDigits = precision
     println("Hit enter key for each beat (q to quit).\n")
     val keyboard = Scanner(System.`in`)
     keyboard.useDelimiter("")
     var shouldContinue = true
     while (shouldContinue) {
     var c: Char
     do {
     c = keyboard.next()[0]
     if (c == 'q') {
     shouldContinue = false
     println("Bye Bye!\n")
     break
     }
     } while (c.toInt() != 10)
     if (shouldContinue) {
     val currentTime = System.currentTimeMillis()
     // Reset if the hit diff is too big.
     if (!hitTimePoints.isEmpty() && currentTime - hitTimePoints.last > resetTime * 1000) {
     // Clear the history.
     hitTimePoints.clear()
     }
     hitTimePoints.add(currentTime)
     if (hitTimePoints.size > 1) {
     val bpm = computeBPM(hitTimePoints.last, hitTimePoints.first, hitTimePoints.size - 1)
     val bpmRepresentation = df.format(bpm)
     println("Tempo: $bpmRepresentation bpm")
     } else {
     println("[Hit enter key one more time to start bpm computation...]")
     }
     while (hitTimePoints.size > sampleSize) {
     hitTimePoints.pop()
     }
     }
     }
    }

    Bref, c'est surtout utile pour :

    • Avoir une base de code cohérente.
    • Vérifier comment un concept Java est censé se transcrire en Kotlin.

    La connaissance libre : https://zestedesavoir.com