简体   繁体   English

CHAQUOPY - 将 Python 对象转换为 Kotlin 类

[英]CHAQUOPY - Convert Python Object to Kotlin class

In the pyhton file:在pyhton文件中:

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:在 Kotlin 文件中:

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

How could I convert that python object into a kotlin class?我怎样才能将该 python 对象转换为 kotlin 类? 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".我不知道如何使用 .toJava(Class) 方法,我试图在那里放置一个与 python 对象具有相同属性的 kotlin 类,但它给了我一个错误“没有足够的信息来推断类型变量 T”。

Chaquopy doesn't support converting between classes on the basis of identical attribute names. Chaquopy 不支持基于相同属性名称的类之间的转换。 However, it easily supports creating Kotlin/Java objects directly from Python code.但是,它很容易支持直接从 Python 代码创建 Kotlin/Java 对象。

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.例如,如果您的 Kotlin 类是com.example.Card ,那么您可以用from com.example import Card的行替换整个 Python Card类,并且returnObj仍然可以正常工作。

Then in Kotlin, you can write this:然后在 Kotlin 中,你可以这样写:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM