Home > database >  CHAQUOPY - Convert Python Object to Kotlin class
CHAQUOPY - Convert Python Object to Kotlin class

Time:11-05

In the pyhton file:

class Card:
    def __init__(self, name, costs):
        self.name = name
        self.costs = costs

def returnObj(string):
    card = Card(string, 2)
    return card

In the Kotlin file:

val pyObject = pythonFile.callAttr("returnObj", "string")

How could I convert that python object into a kotlin class? I don't know how to use the method .toJava(Class), I tried to put there a kotlin class with the same attributes as the python object but it gives me an error "Not enough information to infer type variable T".

CodePudding user response:

Chaquopy doesn't support converting between classes on the basis of identical attribute names. However, it easily supports creating Kotlin/Java objects directly from Python code.

For example, if your Kotlin class is com.example.Card, then you can replace your whole Python Card class with the line from com.example import Card, and returnObj will still work fine.

Then in Kotlin, you can write this:

val card = pythonFile.callAttr("returnObj", "string").toJava(Card::class.java)
  • Related