Tag: 扩展方法

在kotlin的Math类中添加一个扩展函数

我在Kotlin的Math类中增加了一个函数,但是我不能使用它,我之前用MutableList做了这个, MutableList它的工作,但是我不能用Math类来完成。 fun Math.divideWithSubtract(num1: Int, num2: Int) = Math.exp(Math.log(num1.toDouble())) – Math.exp(Math.log(num2.toDouble()))

Gradle构建中未解决的Kotlin扩展函数的引用

我有用Kotlin编写的所有代码构建多个项目Gradle。 有两个项目:普通和客户端。 子项目在中间文件夹,说“演示”。 所以文件夹结构是: project demo client build.gradle common build.gradle build.gradle gradle.properties settings.gradle settings.gradle: rootProject.name = ‘demo’ include ‘demo/client’ include ‘demo/common’ 客户端依赖于通用项目compile project(“:demo/common”) 。 共同项目中有一个扩展function: fun List<Future>.getAll(): Long { var count = 0L this.forEach { it.get() count++ } return count } 如果我尝试在客户端项目中使用它,我会在编译时得到Unresolved reference: getAllexception。 用法: … import org.sandbox.imdg.hazelcast.common.utils.getAll class CassLoader { fun loadCalcData(): Long { […]

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

我怎样才能调用超级的扩展function? 例如: 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扩展lambdas与常规lambda

根据以下源代码,似乎正常的lambda可以与扩展lambdas互换。 fun main(args: Array) { val numbers = listOf(1, 2, 3) filter(numbers, predicate) filter(numbers, otherPredicate) println(“PREDICATE: ${predicate} ” + “\nOTHERPREDICATE: ${otherPredicate} ” + “\nEQUALITY: ${predicate==otherPredicate}”) } val predicate : Int.() -> Boolean = {this % 2 != 0} val otherPredicate : (Int) -> Boolean = {it % 2 != 0} fun filter(list: List, predicate:(Int) -> […]

在Kotlin中共享Float和Double之间扩展函数的实现

注意:这个问题不是generics类,而是generics函数。 (我不认为它是这个的重复:它比这更具体)。 在我们的项目中,我们有一些实用函数来扩展Double和Float ,比如toFixed (受Javascript’s Number.toFixed启发) fun Double.toFixed(digits: Int):String = java.lang.String.format(“%.${digits}f”, this) fun Float.toFixed(digits: Int):String = java.lang.String.format(“%.${digits}f”, this) 如您所见, Double.toFixed和Float.toFixed具有相同的实现。 因为还有其他几个更复杂的扩展function,所以在一个版本(比如Double.toPrecision )中的改进和错误修复必须手动保持同步(使用Float.toPrecision ),这是无聊和容易出错的。 我尝试将重复的实现移动到共享的函数中,但是(正确)它不能在非绑定函数的上下文中访问它。 为了说明,我希望有这样的事情: private fun toFixed(digits: Int):String = java.lang.String.format(“%.${digits}f”, this) fun Double.toFixed = ::toFixed fun Float.toFixed = ::toFixed 如果有什么语言可以摇摆,肯定Kotlin可以! 思考?