假设我有以下代码。
open class Parent
class Child: Parent()
fun <T: Parent> foo(obj: T): T = obj
inline fun <T: Parent> foo(block: () -> T): T = foo(block())
fun <T> bar(obj: T): T = obj
inline fun <T> bar(block: () -> T): T = bar(block())
fun main() {
/* Compile error:
示例:
sealed interface Foo<out T> {
val value: T
}
data class Bar<out K: List<Int>>(override val value: K): Foo<K>
fun <T> processFoo(foo: Foo<T>) {
when (foo) {
is Bar -> foo.value.forEach(::println)
}
}
在以下方面失败:
未解决的参考资料。由于接收器类型不
我在玩反光游戏,我想出了这个问题。当通过::class语法使用绑定类引用时,我得到了一个协变量KClass类型:
fun <T> foo(entry: T) {
with(entry::class) {
this // is instance of KClass<out T>
}
}
正如我可以从文档中学到的那样,这将返回对象的确切类型,以防它是T子类型的实例,因此是方差修饰符。但是,这会阻止检索在T类中声明的属性并获取它们的值(这正是我要做的)
fun <T> foo(entry: T) {
with(entry::c
我想在类层次结构上迭代并打印所有超类:
open class A {}
open class B : A() {}
open class C : B() {}
fun main(args: Array<String>) {
var currentClass = C::class
while(currentClass != Any::class) {
println(currentClass)
currentClass = currentClass.superclass
}
}
但是Kotlin KClass没有supercl
我希望在Throwable上创建一个扩展函数,在给定KClass的情况下,递归地搜索与参数匹配的根原因。以下是一种行之有效的尝试:
fun <T : Throwable> Throwable.getCauseIfAssignableFrom(e: KClass<T>): Throwable? = when {
this::class.java.isAssignableFrom(e.java) -> this
nonNull(this.cause) -> this.cause?.getCauseIfAssignableFrom(e)
e
给定以下代码框架,是否可以确定属性foo实际上是String类型
public class TestIntrospection {
public static class SuperBean<T> {
private T foo;
public T getFoo() { return foo; }
public void setFoo(T foo) { this.foo = foo; }
}
public static class SubBean extends SuperBean<String>
我正在尝试对运行时的泛型进行推理。有几个很棒的库可以做到这一点(例如,、和)。然而,它们的用法有点超出了我的理解。
具体地说,我希望提取一个与子类上下文中的特定字段匹配的表达式。
下面是一个使用gentyref的示例:
import com.googlecode.gentyref.GenericTypeReflector;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
public class ExtractArguments {
public static class Thing<T> {
我现在正在学习Kotlin,做不同的东西来面对问题。
现在,我已经为示例项目提供了简单的DI实现--它可以工作--但是我有关于实现的问题,因为使用与Koin不同(我想他们做得更好)。
在我的DI中,我以列表的形式提供模块,其中Item是由单个和Factory类实现的接口。构造函数需要KClass和工厂方法。这使得模块声明看起来如下所示:
val module: List<Item> = listOf(
Factory(DatabaseKernel::class) { KernelNative() }
)
Koin模块如下所示:
private val model = modu
据我所知,->有善良的*->*->*,((->) r)有善良的*->*。
假设有一个类型的(a->b->c),是否有一种方法来表示(a->b->)
我试过((->) a ((->) b)),但这是错误的。
我试过:
type Kab a b c = (a -> b -> c) -- it is ok
但是它未能在实例声明中使用Kab:
instance KClass (Kab a b) where -- error
我发现唯一有效的方法是声明一个data
data Kab a b c = Kab (a -> b
我有一张KClass到Int的地图。然后,我有一个函数,它有一个具体化的泛型类型。因此,我希望下面的情况给出与Boolean::class相关联的Boolean::class
val kclassToInt = mapOf(Boolean::class to 1, Byte::class to 1, Short::class to 2)
inline fun <reified T> myExpectations() =
assertEquals(1, kclassToInt.getRaw(T::class), "Why doesn't it wor
下面的代码运行良好,对foo.get()扩展函数的调用返回正确的BarImpl类型。
open class Bar
class BarImpl: Bar()
class Foo<T : Bar>
inline fun <reified T : Bar> Foo<T>.get(): T {
return SomeMap(this).get(T::class)
}
class Activity {
lateinit var foo: Foo<BarImpl>
val barImpl = foo.get()
}
但是,当
在以下代码中:
val sum = listOf(1, 2, 3).sumOf { if (it % 2 == 0) 1 else 0 }
Kotlin给出了以下错误:
Kotlin: Overload resolution ambiguity:
public inline fun <T> Iterable<TypeVariable(T)>.sumOf(selector: (TypeVariable(T)) -> Int): Int defined in kotlin.collections
public inline fun <T> Iterabl
我不会每天使用Kotlin,所以我可能会错过1.3.72和1.4.10之间的更改。事实上,过去用旧版本编译的代码现在与新版本中断了。例如,此文件会产生丢失的错误,例如
e: /Users/aalmiray/dev/github/griffon/subprojects/griffon-javafx-kotlin/src/main/kotlin/griffon/javafx/kotlin/collections/reduce/ReducingBindingsExtension.kt: (59, 29): None of the following functions can be called w
我从一张地图myInitialMap开始。我想创建另一个地图myNewMap,它是用myInitialMap初始化的。
val myInitialMap = mapOf<String, Int>("one" to 1, "two" to 2)
val myNewMap = mapOf(myInitialMap)
我得到了错误:
Type mismatch.
Required: Pair<TypeVariable(K), TypeVariable(V)>
Found: Map<String, Int>
如何用myNewMap初始
我有一个函数,它检查它的泛型类型参数,如果该类型是期望值之一,则对该类型执行适当的操作。如果类型是意外的,则会引发异常。
inline fun <reified T> convert(functionName: String, vararg args: Any?): T {
val obj: Any = executeJSFunction(functionName, *args)
val builtInClasses = arrayOf<KClass<*>>(Int::class, String::class, Boolean::class)
使用reified,我可以替换以下函数
private fun <T>createFragmentX(fragmentClass: Class<T>, fragmentArgs: Bundle?): Fragment {
try {
val fragment = fragmentClass.newInstance() as Fragment
fragment.arguments = fragmentArgs
return fragment
} catch (exception: Exception) {
我正在编写一个通用的DeepReadonly类型:
type DeepReadonly<T> = {
readonly [P in keyof T]: true;
};
type A1 = DeepReadonly<number>;
type A2 = DeepReadonly<string>;
type A3 = DeepReadonly<boolean>;
type A4 = DeepReadonly<symbol>;
type A5 = DeepReadonly<never>;
type A6 = Deep
我在泛型类型中迷失了好几个小时。我想简化代码,但是当object是泛型类型时,我不能强制转换object。我如何解决这个问题或另一种简化的方法?(I'm use kotlin 1.2)
sealed class SETTING(override val key: String) : SettingsKeyContract
object optFirstLaunch : SETTING("first_launch"), SettingsKeyContractWithType<Boolean> {
override val defaults = tru
class MyExample {
abstract class Field<in E, T : Any>(private val getter: (E) -> T?) {
fun get(entity: E): T? { return getter(entity) }
}
interface Meta<T: Any> {
fun getFields(): List<MyExample.Field<T, *>>
}
interface MetaRepository {
fun <T :
在下面的代码中,我很难正确地安排输入/输出,以便from()和to()都能按预期工作。我尝试过在属性和函数参数中切换/退出,但最终都会出现错误的输入错误。
class KStateMachine(private val states: List<StateHandler>) {
var currentState: KClass<out StateHandler>
private set
private val handlers:HashMap<KClass<in StateHandler>, Int> = HashMap()
init
我使用反射来发现类及其超类的方法,以及方法参数和返回值的类型。这主要是可行的,但我在一些特殊的通用案例上遇到了麻烦。假设我有一个基类:
package net.redpoint.scratch;
public class Base<E> {
public E getE() { return null; }
}
和一个子类:
package net.redpoint.scratch;
public class Derived extends Base<String> {}
使用反射,我可以遍历派生的方法,获取arg和返回类型(省略了代码,但效果很好)。但是,我也想
当我反映genericType.First of all时,我有一些问题,我有一个这样的类声明:
public class JoyPageWebDTO<T> {
private int recordCount;
private int pageSize;
private int pageIndex;
private List<T> records;
}
T是:
public class AuditSpuWebDTO implements Serializable {
private String indications;
我试图编写一个函数来生成任何类型的属性和值的映射
inline fun <reified T : Any> T.propertiesMap() {
for (property in this::class.memberProperties) {
property.get(this)
}
}
我在property.get(this)中得到了一个编译错误
投影型.禁止使用“公共抽象乐趣获取”(接收器.
我有一个泛型方法,如下所示
private fun <T> getSomething(): T {
return "something" as T
}
如何使用变量T类型调用此方法?
val types = arrayListOf<Type>(String::class.java, Boolean::class.java)
types.forEach { type ->
val something = getSomething<type>() // Unresolved reference: type
}
在运行时,我不
通常情况下,我定义这个函数以获得一个枚举值:
fun <T : Enum<T>> Class<T>.enumValue(name: String): T {
return java.lang.Enum.valueOf(this, name)
}
但有时我不知道给定的Class<*>参数的实际类型:
fun String.toObject(type: Class<*>): Any {
if (type.isEnum) {
// Error: Type mismatch.
// Requir