英文:
Kotlin Extension on a class without Companion object
问题
我有一个简单的Kotlin类,它没有声明伴生对象。
```kt
class Foo
我想要为伴生对象创建一个扩展,即使没有明确指定伴生对象。我不想创建一个空的伴生对象。
fun Foo.Companion.bar()
如何实现?
编辑
以下两者之间的区别是什么:
- 我在
Foo
中添加一个空的伴生对象 - 编译器在
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:
- Me adding an empty companion in
Foo
- 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?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论