0

I can't call clone method in Kotlin. How can I call clone method in case of below:

fun foo(obj: Any?): Int {
   var ret: Int = 0

   if (obj === null) {
      // do Something
   }
   else if (obj is Cloneable) {
      var copied: Cloneable = (obj as Cloneable).clone() // Error occurs 
      // do Something 
   }
}

Cannot access clone: It is protected in Cloneable

msrd0
  • 7,816
  • 9
  • 47
  • 82
Luciano Jeong
  • 325
  • 1
  • 10
  • 1
    The `Cloneable` interface is nothing but a marker, it doesn't export any functions. The `clone` method comes from [`java.lang.Object`](https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#clone--) itself and declares it's `clone` method as protected. So you'd need to check whether that method was made public, e.g. by adding another interface that declares a `public T clone()` – msrd0 Aug 13 '19 at 10:51
  • @msrd0 Would you tell me in code how to check if the method is public? – Luciano Jeong Aug 13 '19 at 11:00
  • If you control the code you'd like to clone, invent a new interface. Otherwise, you'd probably need to use reflection, in which case I'd start by asking yourself whether you really need to do this in the first place, and if there is no other way than cloning (which can be runtime expensive so should be avoided by all means) – msrd0 Aug 13 '19 at 11:02
  • OK, there's no way except reflection... – Luciano Jeong Aug 13 '19 at 11:12
  • If you gave more context I might be able to suggest a different solution than cloning – msrd0 Aug 13 '19 at 11:14

0 Answers0