Tag: 扩展方法

弱引用的扩展方法

我想要创建扩展方法,只有当引用不为null时才会执行方法: fun WeakReference<T>.safe( body : T.() -> Unit) { this.get()?.body() } 用法示例: mTimerView.safe({startTimer(time)}) // OR mTimerView.safe { startTimer(time) } 代替: mTimerView.get()?.stopTimer() 我做错了,因为我得到:“未解决的参考:T”? 或者,也许没有扩展方法有更简单的方法呢?

如何在接收器的函数中使用本地扩展方法?

我发现了一个有趣的事情,但我做不到。 是否有任何方法使本地扩展方法在接收器的函数中可用。 val list = ArrayList<Any>(); fun <T> Array<T>.bind(context: MutableList<in T>, block: Array<T>.() -> Unit) { fun Array<T>.save() { context.addAll(this); } block(); } arrayOf(1, 2, 3).bind(list) { save(); //todo: how to bind extension in execution scope }; 我知道有一种替代方法,为接收器引入另一种类型,但我想避免它。 例如: interface Savable { fun save(); } fun <T> Array<T>.bind(context: MutableList<in T>, block: Savable.() -> Unit) { […]

Java是否支持Swift类的扩展?

在Swift中,您可以创建现有类的扩展,以便在需要时将其他函数添加到现有类中。 这也有助于避免创建现有类的子类。 我只是想知道在Java中是否存在类似的函数? 或者是将其他方法添加到现有java类的唯一方法是创建现有类的子类? 提前感谢任何帮助!

Java相当于C#扩展方法

我正在寻找在对象列表中实现一个功能,就像我在C#中使用扩展方法一样。 像这样的东西: List<DataObject> list; // … List initialization. list.getData(id); 我如何在Java中做到这一点?

Kotlin:我怎样称呼super的扩展功能?

我怎样才能调用超级的扩展功能? 例如: open class Parent { open fun String.print() = println(this) } class Child : Parent() { override fun String.print() { print("child says ") super.print() // syntax error on this } }

何时使用扩展方法?

我正在编写Kotlin代码,其中一个特性是扩展方法,除了使用的语法类似于实例方法调用之外,它们与普通函数实际上是相同的。 正常功能 fun blah(x: Int) { println(x) } val f = blah(1) 扩展方法 fun Int.blah() { println(this) } val f = 1.blah() 据我所知,C#扩展方法的工作原理类似。 原则上,通过将第一个参数的类型移动到函数名称的左侧并相应地调整函数体和调用网站(如本例中),可以将任何非零函数写成扩展方法。 我应该把所有的函数写成扩展方法吗? 他们都没有? 我应该使用什么原则来决定哪些函数可以正常写入,哪些写入作为其中一个输入的扩展方法?

Kotlin:子类如何在超级构造函数调用中使用父级的扩展函数?

子类如何在lambda字段中使用其父类的扩展函数? 考虑这个父类: abstract class Parent(val field: Int.() -> Any) { fun Int.print() = println(this) } 而这个孩子: class Child : Parent({ print() // DOESN'T COMPILE this.print() // DOESN'T COMPILE 5.print() // DOESN'T COMPILE val value = 5 value.print() // DOESN'T COMPILE })

Kotlin:一个类型的扩展函数如何在外部访问?

我经常遇到这种情况,我在一个类型中有抽象扩展函数。 interface PetScript { fun Pet.feed() fun Pet.call() } 具有扩展功能的功能允许非常简约的实现,因为它自动给出this上下文。 不幸的是,我知道使用这些函数的唯一方法是编写传递给扩展的样板标准函数。 interface PetScript { fun Pet.feed() fun Pet.call() fun feed_(pet: Pet) = pet.feed() fun call_(pet: Pet) = pet.call() } 这样我可以使用像这样的功能: val pet = … val script = … script.feed_(pet) script.call_(pet) 有没有更好的,更习惯的方式来使用类型之外的扩展函数?

使全局可用的扩展方法/属性

在Kotlin中,您可以定义现有类的扩展方法和属性: operator inline fun Vector2.plus(other: Vector2) = Vector2(x + other.x, y + other.y) 这允许一个这样做: val result = Vector2(1.1f, 2.3f) + Vector2(2f, 4f) 有没有什么办法可以使这个扩展全局,所以我不必在每个使用这个类的类中导入?

我如何从定义类的外部调用扩展方法?

这是一个最小的例子,演示了这个问题: abstract class Base { abstract fun String.extension(x: Char) } class Derived : Base() { override fun String.extension(x: Char) { // Calling lots of methods on String, hence extension method println("${first()} $length ${last()} ${firstOrNull { it == x }} …") } } 从Java调用扩展方法是微不足道的: Base o = new Derived(); o.extension("hello world", 'l'); 但我不知道如何在纯Kotlin中做到这一点。 String和Base都没有extension方法。