标签: extension-function

从Java访问Kotlin扩展函数

是否可以从Java代码访问扩展函数?

我在Kotlin文件中定义了扩展函数.

package com.test.extensions

import com.test.model.MyModel

/**
 *
 */
public fun MyModel.bar(): Int {
    return this.name.length()
}
Run Code Online (Sandbox Code Playgroud)

哪个MyModel是(生成的)java类.现在,我想用我的普通java代码访问它:

MyModel model = new MyModel();
model.bar();
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用.IDE将无法识别该bar()方法,并且编译失败.

使用kotlin的静态函数可以使用什么:

public fun bar(): Int {
   return 2*2
}
Run Code Online (Sandbox Code Playgroud)

通过使用import com.test.extensions.ExtensionsPackage所以我的IDE似乎正确配置.

我搜索了kotlin文档中的整个Java-interop文件,并搜索了很多内容,但我找不到它.

我究竟做错了什么?这甚至可能吗?

java kotlin extension-function

123
推荐指数
5
解决办法
3万
查看次数

Kotlin之间的区别,应用,让,使用,取出和取消在Kotlin中

我读了很多关于这些物品的Kotlin文件.但我无法理解这么清楚.

有什么用科特林的,,takeIftakeUnless详细?

我需要每个项目的示例.请不要发布Kotlin文档.我需要一个实时示例并使用这些项目的案例.

android kotlin extension-function

19
推荐指数
2
解决办法
9014
查看次数

Kotlin扩展函数数据绑定

是否有可能使用数据绑定扩展功能?XML:

<data>
    <import type="my.package.domain.country.model.City.streetName" />

    <variable
        name="city"
        type="my.package.domain.country.model.City" />
</data>

<TextView
    android:id="@+id/city"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{city.street.streetName()}" />
Run Code Online (Sandbox Code Playgroud)

my.package.domain.country.model.city

data class City(
        val id: String,
        val street: Street
) 

fun City.streetName(): String = street.houseNumber
Run Code Online (Sandbox Code Playgroud)

错误

[kapt]发生异常:android.databinding.tool.util.LoggedErrorException:发现数据绑定错误.****/数据绑定错误****msg:在类my.package.domain.country.model.City中找不到方法streetName()

谢谢 ;)

mvvm kotlin extension-function

19
推荐指数
3
解决办法
2914
查看次数

如何在 Kotlin 中创建具有多个接收器的扩展函数?

我希望我的扩展功能有几个接收器。例如,我希望函数handle能够调用CoroutineScopeIterable实例的方法:

fun handle() {
    // I want to call CoroutineScope.launch() and Iterable.map() functions here
    map {
        launch { /* ... */ }
    }
}
Run Code Online (Sandbox Code Playgroud)

我认为这可能有效:

fun <T> (Iterable<T>, CoroutineScope).handle() {}
Run Code Online (Sandbox Code Playgroud)

但这给了我一个错误:

Function declaration must have a name
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用参数创建函数,但是

单个函数是否可以有多个接收器以及如何在没有参数的情况下做到这一点?

android kotlin extension-function kotlin-coroutines kotlin-context-receivers

18
推荐指数
1
解决办法
1万
查看次数

kotlin中的全局扩展功能

嘿,我想在kotlin中创建一个类,它将包含我将在几个地方使用的所有扩展函数,例如:

class DateUtils {
    //in this case I use jodatime
    fun Long.toDateTime() : DateTime = DateTime(this)
    fun String.toDateTime() : DateTime = DateTime.parse(this)
}


class SomeClassWithNoConnectionToDateUtils {
    fun handleDataFromServer(startDate: String) {
        someOtherFunction()
        //startDate knows about toDateTime function in DateUtils 
        startDate.toDateTime().plusDays(4)
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法执行此类操作

kotlin extension-function

12
推荐指数
1
解决办法
3944
查看次数

为"数字类"重载+和+ =运算符

我想为封装简单Numbers的类创建扩展函数.例如DoubleProperty.我遇到了问题,我不能同时超载++=操作员.

我不想创建一个通过以下测试的行为:

class DoublePropertyTest {
    lateinit var doubleProperty: DoubleProperty

    @Before
    fun initialize() {
        doubleProperty = SimpleDoubleProperty(0.1)
    }

    @Test
    fun plus() {
        val someProperty = doubleProperty + 1.5
        assertEquals(someProperty.value, 1.6, 0.001)
    }

    @Test
    fun plusAssign() {
        val someProperty = doubleProperty
        doubleProperty += 1.5 //error if + and += are overloaded

        assert(someProperty === doubleProperty) //fails with only + overloaded
        assertEquals(doubleProperty.value, 1.6, 0.001)
    }
}
Run Code Online (Sandbox Code Playgroud)

它可以使用这些扩展函数实现:

operator fun ObservableDoubleValue.plus(number: Number): DoubleProperty 
    = SimpleDoubleProperty(get() + number.toDouble()) …
Run Code Online (Sandbox Code Playgroud)

operator-overloading kotlin extension-function

9
推荐指数
1
解决办法
2968
查看次数

如何在 Typescript 中编写 Kotlinesque 扩展函数?

Kotlin如果我有interface这样的:

interface User {
    val name: String
    val email: String
}
Run Code Online (Sandbox Code Playgroud)

我可以在代码中的任何位置编写这样的扩展函数:

fun User.toUserDto(): UserDto {
    TODO()
}
Run Code Online (Sandbox Code Playgroud)

打字稿中,如果我有类似的interface

export default interface User {
    name: string;
    email: string;
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能以类似的方式增强它?这是该语言的最佳实践吗?有没有我不知道的替代方案?

javascript extension-methods kotlin typescript extension-function

7
推荐指数
1
解决办法
528
查看次数

测试类内的扩展函数

如果我们想在类型上测试扩展函数,我们可以创建这种类型的实例,调用函数并检查返回的值.但是如何测试类中定义的扩展函数呢?

abstract class AbstractClass<T> {
    fun doStuff(): T = "Hello".foo()

    abstract fun String.foo(): T
}

class SubClass1: AbstractClass<Int>() {
    override fun String.foo(): Int = 1
}

class SubClass2: AbstractClass<Boolean>() {
    override fun String.foo(): Boolean = true
}
Run Code Online (Sandbox Code Playgroud)

我们如何测试方法的逻辑foo()中类SubClass1SubClass2?它甚至可能吗?

我知道我可以改变设计来测试它.我有两种可能性:

  1. 不要使用扩展功能.¯\ _(ツ)_ /¯

    abstract class AbstractClass<T> {
        fun doStuff(): T = foo("Hello")
    
        abstract fun foo(string: String): T
    }
    
    class SubClass1: AbstractClass<Int>() {
        override fun foo(string: String): Int = 1
    }
    
    Run Code Online (Sandbox Code Playgroud)

    然后我们可以创建一个对象SubClass1,调用foo()并检查返回的值. …

unit-testing kotlin extension-function kotlin-extension

6
推荐指数
1
解决办法
865
查看次数

私有顶层扩展函数与类内部私有扩展函数的区别

我们目前正在将我们的项目切换到 Kotlin,并遇到以下问题:

我们只需要在给定的类中使用某个扩展函数。因此,我们有两种可能性:(1)private在文件顶层声明扩展函数或(2)private在类内部声明扩展函数。

遵循MCVE

顶级示例(文件C1.kt):

private fun String.double() = this.repeat(2)
class C1 {
    init {
        println("init".double())
    }
}
Run Code Online (Sandbox Code Playgroud)

内部类示例(文件C2.kt):

class C2 {
    private fun String.double() = this.repeat(2)
    init {
        println("init".double())
    }
}
Run Code Online (Sandbox Code Playgroud)

问题:

  1. 这两种方法有什么区别,只是在C1.kt扩展函数String.double()中其他可能的文件成员(例如同一文件中的其他类)也可以看到?

  2. 由于我们希望实现“尽可能 kotlinic”的代码,我们想知道这两种方法中的哪一种是建议的。上面的例子有官方建议/风格指南吗?我认为声明扩展函数尽可能接近其预期用途被认为是一种很好的做法,因此在上面的例子中C2会建议结构?

extension-methods member kotlin extension-function toplevel

6
推荐指数
1
解决办法
1244
查看次数

在 Kotlin 中仅向具有多个类型参数的扩展函数提供一个类型参数

介绍

在 Kotlin 中,我有一个通用转换扩展函数,它可以简化从一种this类型的对象C到另一种类型的对象T(声明为receiver)的转换,并提供额外的转换action,该转换视为receiver原始this对象并提供对原始对象的访问:

inline fun <C, T, R> C.convertTo(receiver: T, action: T.(C) -> R) = receiver.apply {
    action(this@convertTo)
}
Run Code Online (Sandbox Code Playgroud)

它的使用方式如下:

val source: Source = Source()
val result = source.convertTo(Result()) {
    resultValue = it.sourceValue
    // and so on...
}
Run Code Online (Sandbox Code Playgroud)

我注意到我经常在由无参数构造函数创建的函数上使用这个函数,并且认为通过创建基于其类型自动构建receivers的附加版本来进一步简化它会很好,如下所示:convertTo()receiver

inline fun <reified T, C, R> C.convertTo(action: T.(C) -> R) = with(T::class.constructors.first().call()) {
    convertTo(this, action) // calling the first version of convertTo() …
Run Code Online (Sandbox Code Playgroud)

generics default-constructor type-constraints kotlin extension-function

5
推荐指数
1
解决办法
1116
查看次数