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

问题描述 投票:0回答:2

假设我想将 java 方法

Log.d(String, String)
分配给方法类型
x
的变量
(String, String) -> Int
,我会这样做:

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)
但是我如何告诉编译器我想要哪一种?

kotlin method-reference
2个回答
6
投票

这里目前不支持消歧(稍后会支持)。

作为解决方法,您可以使用 lambda 表达式:

{ s, s1 -> android.util.Log.d(s, s1) }

0
投票

要解决此问题,您必须显式指定变量的类型:

fun foo(i: Int) = 1
fun foo(str: String) = "AAA"

fun main() {
  val fooInt: (Int) -> Int = ::foo
  println(fooInt(123)) // 1
  val fooStr: (String) -> String = ::foo
  println(fooStr("")) // AAA
}

带有构造函数的情况:

class StudentId(val value: Int)
data class UserId(val value: Int) {
   constructor(studentId: StudentId) : this(studentId.value)
}

fun main() {
   val intToUserId: (Int) -> UserId = ::UserId
   println(intToUserId(1)) // UserId(value=1)

   val studentId = StudentId(2)
   val studentIdToUserId: (StudentId) -> UserId = ::UserId
   println(studentIdToUserId(studentId)) // UserId(value=2)
}
© www.soinside.com 2019 - 2024. All rights reserved.