简体   繁体   English

在 Scala 中调用 Kotlin 的重载方法

[英]Calling overloaded method of Kotlin in Scala

Here are two functions, one in kotlin.kt :这里有两个函数,一个在kotlin.kt中:

interface TraitA

fun <T : TraitA> foo(a: Any, f: (T) -> Unit) {
    TODO()
}

another adapter function in Scala.scala Scala.scala 中的另一个适配器Scala.scala

import KotlinKt.foo

object Scala {
  def adapter[E <: TraitA](f: (E) => Unit): Unit = {
    foo[E](None, { a =>
      // Do something

      kotlin.Unit.INSTANCE
    })
  }
}

Till this moment, it compiles.直到这一刻,它编译。 But when I overload this function in Kotlin:但是当我在 Kotlin 中重载这个 function 时:

interface TraitA

fun <T : TraitA> foo(f: (T) -> Unit) {
    TODO()
}

fun <T : TraitA> foo(a: Any, f: (T) -> Unit) {
    TODO()
}

Scala fails to compile with the following error: Scala 无法编译并出现以下错误:

> Task :scala:compileScala
[Error] E:\Documents\Projects\Temp\kotlin-example\scala\src\main\scala\Scala.scala:5: missing parameter type
one error found

It tells me to add parameter type, so I added it:它告诉我添加参数类型,所以我添加了它:

import KotlinKt.foo

object Scala {
  def adapter[E <: TraitA](f: (E) => Unit): Unit = {
    foo[E](None, { (a: E) =>
      kotlin.Unit.INSTANCE
    })
  }
}

The compiler throws other error after the change:更改后编译器会引发其他错误:

[Error] E:\Documents\Projects\Temp\kotlin-example\scala\src\main\scala\Scala.scala:5: overloaded method foo with alternatives:
  (x$1: Object,x$2: kotlin.jvm.functions.Function1[_ >: E, kotlin.Unit])Unit <and>
  (x$1: kotlin.jvm.functions.Function1[_ >: E, kotlin.Unit])Unit
 cannot be applied to (None.type, E => kotlin.Unit)
one error found

I tried to construct a Kotlin Function1 "explicitly":我试图“明确地”构造一个 Kotlin Function1

import KotlinKt.foo

import kotlin.jvm.functions.{Function1 => KF1}

object Scala {
  def adapter[E <: TraitA](f: (E) => Unit): Unit = {
    val kf: KF1[E, kotlin.Unit] = { e => f(e); kotlin.Unit.INSTANCE }

    foo[E](None, kf)
  }
}

It compiles and works well.它编译并运行良好。 But it is too circuitous, is there a prettier way to call foo[T](Any, Function1[_ >: T, kotlin.Unit]) ?但是太绕了,有没有更漂亮的方式调用foo[T](Any, Function1[_ >: T, kotlin.Unit])

Try to add implicit conversion尝试添加隐式转换

implicit def scalaToKotlin(u: Unit): kotlin.Unit = kotlin.Unit.INSTANCE

Then然后

def adapter[E <: TraitA](f: (E) => Unit): Unit = {
  foo(None, (e: E) => f(e))
}

compiles.编译。

Scala 2.13.2, Kotlin 1.3.50, sbt 1.3.8 + kotlin-plugin 2.0.0. Scala 2.13.2、Kotlin 1.3.50、sbt 1.3.8 + kotlin 插件 2.0.0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM