Advertisement
pavelperc

converter

Feb 9th, 2019
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.55 KB | None | 0 0
  1.  
  2.  
  3. sealed class Measure(
  4.         val short: String,
  5.         val normal: String,
  6.         val plural: String,
  7.         val multiplier: Double,
  8.         val shift: Double = 0.0
  9. )
  10.  
  11. class Dist(
  12.         short: String,
  13.         normal: String,
  14.         plural: String,
  15.         multiplier: Double
  16. ) : Measure(short, normal, plural, multiplier)
  17.  
  18. class Weight(
  19.         short: String,
  20.         normal: String,
  21.         plural: String,
  22.         multiplier: Double
  23. ) : Measure(short, normal, plural, multiplier)
  24.  
  25. class Tempr(
  26.         short: String,
  27.         normal: String,
  28.         plural: String,
  29.         multiplier: Double,
  30.         shift: Double
  31. ) : Measure(short, normal, plural, multiplier, shift)
  32.  
  33. val allMeasures = listOf(
  34.         Dist("a", "a", "a", 1.0),
  35.         Weight("b", "b", "b", 2.0),
  36.        
  37.         Tempr("degree", "c", "", 1.0, 0.0),
  38.         Tempr("fahrenheit", "f", "", 1.8, 32.0),
  39.         Tempr("kelvin", "k", "", 1.0, 273.5)
  40. )
  41.  
  42. val nameToMeasure = allMeasures
  43.         .flatMap { m ->
  44.             listOf(m.short, m.normal, m.plural).map { name -> name to m }
  45.         }.toMap()
  46.  
  47.  
  48. fun main(args: Array<String>) {
  49.     // 23 f to k
  50.    
  51.     val m1 = nameToMeasure.getValue("f")
  52.     val m2 = nameToMeasure.getValue("k")
  53.     val input = 23
  54.    
  55.     if (m1::class != m2::class) {
  56.         throw IllegalStateException("incomparable types: ${m1::class.simpleName} and ${m2::class.simpleName}")
  57.     }
  58.    
  59.     val inDefault = (input - m1.shift) / m1.multiplier
  60.    
  61.     val output = inDefault * m2.multiplier + m2.shift
  62.     println(output)
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement