英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论