Kotlin

[코틀린 코딩 습작] Tuple

[하마] 이승현 (wowlsh93@gmail.com) 2021. 6. 7. 11:51

class Tuple(vararg elements: Any) {
  val elements: Array<Any>
  
  init {
    this.elements = elements as Array<Any>
  }
  
  fun get(index: Int): Any {
    return elements[index]
  }
  
  fun size(): Int {
    return elements.size
  }
  
  override fun hashCode(): Int {
    return Arrays.deepHashCode(elements)
  }
  
  override fun equals(o: Any?): Boolean {
    if (this === o) return true
    if (o == null || javaClass != o.javaClass) return false
    val other = o as Tuple
    return Arrays.deepEquals(elements, other.elements)
  }
  
  override fun toString(): String {
    return Arrays.deepToString(elements)
  }
  
  companion object {
    val EMPTY = Tuple()
    fun of(vararg elements: Any?): Tuple {
      return Tuple(*elements as Array<out Any>)
    }
  }
}


data class  Tuple2<T1,T2>(val _1: T1, val _2: T2) : Serializable {
  override fun toString(): String {
   return "($_1, $_2)"
  }
}

data class  Tuple3<T1,T2,T3>(val _1: T1, val _2: T2, val _3: T3) : Serializable{
  override fun toString(): String {
    return "($_1, $_2, $_3)"
  }
}

fun main() {

  val tuple = Tuple("hi", 2, 1.2)
  println(tuple.size())

 val tuple2 = Tuple2<String, Int>("hi", 1)
  println(tuple2)
  val tuple3 = Tuple3<String, Int, Double>("hi", 1, 1.2)
  println(tuple3)
  
}