Tag: 类型推断

我们应该用显式类型在Java中实例化一个地图对象吗?

有朋友告诉我,在实践/行业中我们应该写: Map<Class1, Class2> map = new HashMap<>(); 代替 Map<Class1, Class2> map = new HashMap<Class1, Class2>(); 这种编码风格有什么特别的原因吗?

在Kotlin中可以交叉投射吗?

我有一个像Java这样的方法: public <T extends A & B> methodName(T arg, …) 其中A是一个类,B是一个接口。 在我的kotlin类中,我有另一个C类型的variable ,我希望实现以下功能: if (variable is A && variable is B) { methodName(variable, …) } else { // do something else } 是否有可能正确地投下variable以便它可以作为参数没有错误? 目前,该variable具有setter方法,所以智能铸造不可用。 但是,我也用一个本地的val测试它,并且这个值被推断为具有类型Any而不起作用。

为lambda参数类型输入推断

Kotlin无法编译此代码,因为编译器指出“Error:Smart cast to'Nothing'是不可能的,因为'accumulator'是一个复杂的表达式” 你的olde函数被称为你所期望的,也就是说,我想返回indexOfMax – 但更重要的是理解为什么“聪明的演员”未能投射到accumulator一个Int fun indexOfMax(a: IntArray): Int? { return a.foldIndexed(null) { index, accumulator, element -> return if (accumulator is Int) { var i:Int = accumulator return if (accumulator == null) index else if (element > a[i]) index else accumulator } else accumulator } } 编辑 是的,接受的答案是有效的! 这是解决方案: fun indexOfMax(a: IntArray): Int? { […]

无法在Kotlin中“findViewById”。 获取错误“类型推断失败”

当我尝试按ID查找RecycleView时,出现以下错误。 错误: –类型推断失败:没有足够的信息来推断参数T 码: class FirstRecycleViewExample : AppCompatActivity() { val data = arrayListOf<String>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.first_recycleview) val recycler_view = findViewById(R.id.recycler_view) as RecyclerView ///IN THIS LINE I AM GETTING THE ERROR data.add("First Data") data.add("Second Data") data.add("Third Data") data.add("Forth Data") data.add("Fifth Data") //creating our adapter val adapter = CustomRecycleAdapter(data) //now adding the adapter […]

类型推断失败:没有足够的信息来推断参数请明确指定

我正在尝试在Kotlin上写一个Vaadin应用程序。 对于数据绑定,Vaadin 8现在提供了类型安全数据绑定的可能性。 在科特林,我会期待这样的工作: class LoginModel { var username: String = "" var password: String = "" } class LoginView : FormLayout() { val name = TextField("name") val password = TextField("password") val loginButton = Button("login") init { val binder = Binder<LoginModel>() binder.forField(name).bind( { it.username }, { bean, value -> bean.username = value }) //… } […]

我如何知道Kotlin的推断类型?

(我使用Kotlin 1.1.2-2) 例如,如何知道表达式的推断类型if (boolean_value) 1 else 2.0 ? kotlinc-jvm不显示类型。 javaClass也没有帮助,因为它显示计算值的类型而不是表达式。 >>> (if (true) 1 else 2.0).javaClass.name java.lang.Integer >>> (if (false) 1 else 2.0).javaClass.name java.lang.Double >>> val v: Double = if (false) 1 else 2.0 error: the integer literal does not conform to the expected type Double val v: Double = if (false) 1 else 2.0 […]

Kotlin类型推断失败

比方说,我们有一个这样的类的第三方Java库: //—————————————————————————————- package foo; public final class Functions { public interface VoidFunc0 { void call(); } public interface VoidFunc1<T> { void call(T t); } @SuppressWarnings("unchecked") public static <T> NoOpFunc<T> noOp() { return new NoOpFunc(); } /*public*/ static final class NoOpFunc<T> implements VoidFunc0, VoidFunc1<T> { @Override public void call() { /* deliberately no op */} @Override […]