Search code examples
androidiosanyobject

Android - AnyObject for Android like iOS Swift 2


I need help, This is example for AnyObject Class in Swift.

class OtherClass {
   private var myValue: String?
   func setValue(myValue: String) {
      self.myValue = myValue
   }
   func getValue() -> String {
      return myValue!
   }
}

class MyClass {
   init() {
      let otherClass = OtherClass()
      otherClass.setValue("Value here!")
      let myValue = getValue(otherClass) as? String
      print(myValue) // output is Value here!
   }
   func getValue(object: AnyObject) -> AnyObject {
      let myObject = object as! OtherClass
      return myObject.getValue()
   }
}

We can add OtherClass object to parameter of getValue method. You can see, the parameter method is AnyObject not OtherClass. But in android i cannot do that. So, is possible use AnyObject Class in Android like in iOS ?


Solution

  • You need to use Java Object class. Otherwise you can create your own class, extended by all OtherClass and use it as input type parameter.

    You could give a look to Java Generic Types too (but it's more advanced and maybe it's not useful in this case)

    Swift AnyObject Doc:

    The protocol to which all classes implicitly conform.

    Java Object Doc:

    Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.