Tag: 方法参考

如何解决方法引用中的过载歧义?

假设我想将java方法Log.d(String, String)赋值给方法类型(String, String) -> Int的变量x ,我这样做: val x: (String, String) -> Int = android.util.Log::d 编译器说: Error:(50, 56) Overload resolution ambiguity: public open fun d(tag: kotlin.String!, msg: kotlin.String!): kotlin.Int defined in android.util.Log public open fun d(tag: kotlin.String!, msg: kotlin.String!, tr: kotlin.Throwable!): kotlin.Int defined in android.util.Log 显然还有第二种方法Log.d(String, String, Throwable)但是如何告诉编译器我想要哪一个呢?

RxKotlin使用方法引用collectInto()MutableList

以下代码是我尝试将RxJava示例转换为Kotlin。 它应该收集一串Int到MutableList ,但是我得到了大量的错误。 val all: Single<MutableList<Int>> = Observable .range(10, 20) .collectInto(::MutableList, MutableList::add) 错误: Error:(113, 36) Kotlin: Type inference failed: Not enough information to infer parameter T in inline fun <T> MutableList(size: Int, init: (index: Int) -> T): MutableList<T> Please specify it explicitly. Error:(113, 49) Kotlin: One type argument expected for interface MutableList<E> : List<E>, MutableCollection<E> […]

超类方法的引用方法

如何使用方法引用来引用超类方法? 在Java 8中,您可以执行SubClass.super::method 。 Kotlin的语法是什么? 期待你的回复! 结论 感谢Bernard Rocha! 语法是SubClass::method 。 不过要小心。 在我的情况下,子类是一个泛型类。 不要忘记宣布这样的: MySubMap<K, V>::method 。 编辑 它在Kotlin仍然不起作用。 她是一个超级类方法引用的Java 8中的例子: public abstract class SuperClass { void method() { System.out.println("superclass method()"); } } public class SubClass extends SuperClass { @Override void method() { Runnable superMethodL = () -> super.method(); Runnable superMethodMR = SubClass.super::method; } } […]

使用函数引用重写Kotlin中的Java代码会发生SAM类型冲突

我有一个示例Java代码使用方法引用,我想重写到Kotlin。 Java版本使用方法参考,解决方案简短明了。 但另一方面,我不能在Kotlin中使用方法引用。 我设法编写的唯一版本是下面介绍的一个。 看起来像Function3 { s: String, b: Boolean, i: Int -> combine(s, b, i) }可以用更简洁的方式编写(如果可能的话,方法引用将是完美的)。 我是Kotlin新手,所以我会感激任何线索。 Java的 import io.reactivex.Observable; public class TestJava { Observable<String> strings() { return Observable.just("test"); } Observable<Boolean> booleans() { return Observable.just(true); } Observable<Integer> integers() { return Observable.just(1); } void test() { Observable.combineLatest(strings(), booleans(), integers(), this::combine); } double combine(String s, boolean […]