Kotlin中一个没有伴生对象的类的扩展

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

Kotlin Extension on a class without Companion object

问题

我有一个简单的Kotlin类它没有声明伴生对象

```kt
class Foo

我想要为伴生对象创建一个扩展,即使没有明确指定伴生对象。我不想创建一个空的伴生对象。

fun Foo.Companion.bar()

如何实现?

编辑

以下两者之间的区别是什么:

  1. 我在Foo中添加一个空的伴生对象
  2. 编译器在Foo中添加一个空的伴生对象

<details>
<summary>英文:</summary>

I have a simple Kotlin class, that does not declare a companion object.

```kt
class Foo

I would love to create an extension for companion object, even if one is not specified. I do not want to create an empty companion object.

fun Foo.Companion.bar()

How?

EDIT

What is the difference between:

  1. Me adding an empty companion in Foo
  2. compiler adds an empty companion in Foo

?

答案1

得分: 1

I would love to create an extension for companion object, even if one is not specified.

为什么?

如何?

You can't. An extension, by definition, is something that extends ... something. You can't extend a non-existent entity. Remember that extension functions are basically static functions that take an instance of the extending object as the first parameter. So your example:

fun Foo.Companion.bar()

Would translate to:

public static void bar(Foo.Companion objectBeingExtended) { }

如果 Foo.Companion 不存在,那应该如何工作?

英文:

> I would love to create an extension for companion object, even if one is not specified.

Why?

> How?

You can't. An extension, by definition, is something that extends ... something. You can't extend a non-existent entity. Remember that extension functions are basically static functions that take an instance of the extending object as the first parameter. So your example:

fun Foo.Companion.bar()

Would translate to:

public static void bar(Foo.Companion objectBeingExtended) { }

How is that supposed to work if Foo.Companion doesn't exist?

huangapple
  • 本文由 发表于 2023年4月7日 04:32:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75953527.html
匿名

发表评论

匿名网友

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

确定