如何在Kotlin中创建这个界面?

huangapple go评论58阅读模式
英文:

How to create this interface in Kotlin?

问题

把 TypeScript 接口转换成 Kotlin 时遇到问题。原始 TypeScript 接口如下:

interface Test {
  'some-key': boolean
}

在 Kotlin 中,你可以尝试将它转换为如下形式:

interface Test {
  val `some-key`: Boolean
}

这里我们使用了反引号(``)来包裹属性名称,因为 Kotlin 中某些属性名称可能包含特殊字符,需要用反引号来转义。

英文:

I have this interface in typescript that looks like this:

interface Test {
  'some-key' : boolean
}

Anyone know how to convert this to kotlin? When I tried to use this in kotlin, like this:

interface Test {
  val 'some-key' : boolean
}

it is saying: "Expecting property name or receiver type"

答案1

得分: 3

some-key 不是一个有效的 Kotlin 标识符。你需要使用 some_key 或(更符合惯例的)someKey 来定义接口中的属性。

interface Test {
  val someKey: Boolean
}

然后实现类将被期望定义 val someKey 属性作为 Boolean。

请注意,Kotlin 不像 TypeScript。Kotlin 是名义类型的。因此,接口 Test 并不会自动封装所有类中名为 someKey 的 Boolean。相反,它特别作为一种超类型,供选择实现 Test 接口的类使用。

如果你真正想要的是一种“只包含”一个 Boolean 值的类型,而不是封装包含 Boolean 的抽象接口,那么你可以使用 data class

data class Test(val someKey: Boolean)

这是一种非抽象的类型,可以实例化。它具体包含一个 Boolean 值,可以被调用者自由访问。

如果你确实想要在 Kotlin 中使用类似 some-key 这样的键名,你可以用反引号将其括起来。请注意,你库的用户也必须这样做。

data class Test(val `some-key`: Boolean)
英文:

some-key is not a valid Kotlin identifier. You'll need to use some_key or (more idiomatically) someKey to define a property in your interface.

interface Test {
  val someKey: Boolean
}

Then implementors will be expected to define the val someKey property as a Boolean.

Do note that Kotlin is not like Typescript. Kotlin is nominally typed. So the interface Test does not magically encapsulate all classes ever written with a Boolean called someKey. Instead, it specifically acts as a supertype to classes that opt in to implementing the Test interface.

If what you're looking for is a type that "just contains" a Boolean, not an abstract interface that encapsulates the idea of containing a Boolean, then you want a data class.

data class Test(val someKey: Boolean)

This is a type that is not abstract and can be instantiated. It contains one Boolean concretely, which can be accessed freely by callers.

If you really do want to use something like some-key as a key name in Kotlin, you can surround it in backticks. Note that users of your library will have to do the same.

data class Test(val `some-key`: Boolean)

huangapple
  • 本文由 发表于 2023年2月24日 10:37:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75552149.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定