如何在构造函数中指定具有通用类型的Kotlin函数参数?

huangapple go评论47阅读模式
英文:

How can I specify a Kotlin function parameter with generic type in a constructor?

问题

我想传递一个接受类型 T 并返回类型 T 的函数给构造函数。其中 T 是相同的类型。

class Foo(
val f: (T) -> T
)


问题是 T 不能是类的泛型类型——想象一下传递一个恒等函数——它将在类的不同上下文中使用。

val s: String = f("a string")
val i: Int = f(42)


有没有办法指定 f 的类型?
英文:

I want to pass a function that takes a T and returns a T, where T is the same type, to a constructor

So something like

class Foo(
    val f: (T) -> T
)

The thing is that the T can't be a generic type of the class - think passing an identity function - it will be used inside the class in different contexts

   val s: String = f("a string")
   val i: Int = f(42)

Is there any way to specify the type of f?

答案1

得分: 1

这是您要翻译的内容:

Instead of using the raw function type, I can define an interface:

interface ID {
    operator fun <R> invoke(r: R): R
}

then 

class Foo(
    val f: Identity
)

inside the class

   val s = f("a string")
   val i = f(42)

I can create an id with

val id = object: ID {
    override fun <R> invoke(r: R): R = r
}

and instantiate Foo with it

val aFoo = Foo(id)
英文:

Instead of using the raw function type, I can define an interface:

interface ID {
    operator fun <R> invoke(r: R): R
}

then

class Foo(
    val f: Identity
)

inside the class

   val s = f("a string")
   val i = f(42)

I can create an id with

val id = object: ID {
    override fun <R> invoke(r: R): R = r
}

and instantiate Foo with it

val aFoo = Foo(id)

huangapple
  • 本文由 发表于 2023年2月24日 04:45:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75550150.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定