可能重复:
可能导致精度损失的不同行为
我在编译时发现Java强类型检查不一致.请看下面的代码:
int sum = 0;
sum = 1; //is is OK
sum = 0.56786; //compile error because of precision loss, and strong typing
sum = sum + 2; //it is OK
sum += 2; //it is OK
sum = sum + 0.56787; //compile error again because of automatic conversion into double, and possible precision loss
sum += 0.56787; //this line is does the same thing as the previous line, but it does not give us a compile error, …Run Code Online (Sandbox Code Playgroud) 假设我们有两个活动.
A - 主要活动,即"启用主启动器"(适当的意图过滤器等)
B - 具有singleTask规范的任务根活动(此活动只能有一个实例)和自定义taskAffinity(用于区分主要任务)根).
假设B代表一个任务,只有当它没有完成时才有效 - 返回它或者在完成它之后从最近的任务再次启动它不是一个选项.
在某些时候 - A开始B开始新任务.目标是在用户完成B时从最近的任务列表中删除B.用户可以从B导航到其他任务(使用主页长按)然后导航回B,只要它没有完成.从启动器启动A不会将B带到前台,因为它们具有不同的任务关联性.
Android将B识别为任务的根,因此即使B已完成,B也会在最近的任务列表中可见,并且用户始终可以返回到该任务.使用A将B移动到一个任务不是解决方案,因为在B运行的时间 - 用户应该能够在A和B任务之间切换.将excludeFromRecents添加到B的清单会将其从最近的任务列表中完全删除,这也是不好的解决方案.
怎么实现呢?(对不起,我的英语不好)
我有这样的java代码:
String getData(Object obj)
{
if (obj instanceof String[])
{
String[] arr = (String[]) obj;
if (arr.length > 0)
{
return arr[0];
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
我该如何将此代码转换为Kotlin?我尝试过自动Java到Kotlin转换,结果如下:
fun getData(obj:Any):String {
if (obj is Array<String>)
{
val arr = obj as Array<String>
if (arr.size > 0)
{
return arr[0]
}
}
return null
}
Run Code Online (Sandbox Code Playgroud)
这是我从kotlin编译器得到的错误:
无法检查已擦除类型的实例:Array <String>
我认为类型擦除仅适用于泛型类型,而不适用于简单的强类型Java数组.我该如何正确检查传递的数组实例的组件类型?
编辑
此问题与泛型类型检查问题不同,因为Java数组不是泛型类型,并且使用is运算符的常规Kotlin类型检查会导致编译时错误.
谢谢!
请看这段代码:
fun localVarNullSafety1(){
var number: Double? = 3.0
val sum = 2.0 + number // does not compile (Type mismatch: inferred type is Double? but Double was expected)
}
fun localVarNullSafety1(){
var number: Double? = null
number = 3.0
val sum = 2.0 + number // compiles fine
}
Run Code Online (Sandbox Code Playgroud)
我认为上面的代码由语义上相同的函数组成 - 局部变量不会超出范围,并且它们对于执行线程来说是本地的。在我看来,第一个函数没有理由不编译。
我认为 Kotlin 的智能转换应该考虑变量初始化。
我错过了一些明显的事情吗?