简体   繁体   English

在Kotlin我如何转换Int?到国际

[英]In Kotlin How Can I Convert an Int? to an Int

I'm using a HashMap<Int, Int> in Kotlin and when I get out of it the return type is Int? 我使用HashMap<Int, Int>在科特林,当我get了它的返回类型是Int? .

How can I convert the Int? 我如何转换Int? to an Int ? Int

So far I've tried using Int?.toInt() , but that seems to be returning an Int? 到目前为止,我已经尝试使用Int?.toInt() ,但这似乎是返回一个Int? .

I'm writing a Fibonacci function, and my code looks like: 我正在写一个Fibonacci函数,我的代码看起来像:

val fibMemo : Map<Int, Int> = HashMap<Int,Int>()
fun fibN(n:Int) : Int {
    if (n == 0 || n == 1) return 1
    if (fibMemo.containsKey(n))
        // Error here: Type mismatch: inferred type is Int? but Int was expected
        return fibMemo.get(n)?.toInt()
    else {
        val newNum : Int = fibN(n-1) + fibN(n-2)
        fibMemo.put(n, newNum)
        return newNum
    }
}

The direct answer, use the !! 直接回答,使用!! operator to assert that you trust a value is NOT null and therefore changing its type to the non null equivalent. 运算符断言您信任某个值是非null,因此将其类型更改为非null等效值。 A simple sample showing the assertion allowing the conversion (which applies to any nullable type, not just Int? ) 一个简单的示例,显示允许转换的断言(适用于任何可空类型,而不仅仅是Int?

val nullableInt: Int? = 1
val nonNullableInt: Int = nullableInt!! // asserting and smart cast

Another way to convert a value is via a null check. 转换值的另一种方法是通过空检查。 Not useful in your code above, but in other code (see Checking for null in conditions ): 在上面的代码中没有用,但在其他代码中(请参阅在条件中检查null ):

val nullableInt: Int? = 1
if (nullableInt != null) {
   // allowed if nullableInt could not have changed since the null check
   val nonNullableInt: Int = nullableInt
}

This questions is also answered by the idiomatic treatment of nullability question: In Kotlin, what is the idiomatic way to deal with nullable values, referencing or converting them 这个问题也可以通过对可空性问题的惯用处理来回答: 在Kotlin中,处理可空值,引用或转换它们的惯用方法是什么?

In order to convert an Int? 为了转换Int? to an Int use the sure() method. Int使用sure()方法。

The offending line should look like: 违规行应如下所示:

return fibMemo.get(n).sure()

Call to method sure() is Kotlin way (soon to be replaced by special language construct) to ensure non-nullability. 调用方法sure()是Kotlin方式(很快将被特殊语言结构替换)以确保不可空性。 As Java has not notation of nullable and non-nullable types we need to take some care on integration point. 由于Java没有可空和非可空类型的表示法,我们需要注意集成点。 Please read amazing story of null-safety in Kotlin documentation. 请阅读Kotlin文档中关于零安全的惊人故事。

source 资源

Warning : the above information doesn't hold anymore. 警告 :上述信息不再存在。 sure has been replaced by !! sure已被!!取代!! . See: http://blog.jetbrains.com/kotlin/migrating-sure/ 请参阅: http//blog.jetbrains.com/kotlin/migrating-sure/

You also can use getOrPut function to avoid contains/put in you code. 您还可以使用getOrPut函数来避免包含/放入代码。 See 看到

val fibMemo = HashMap<Int, Int>()
fun fibN(n: Int): Int = when {
    n < 0 -> throw IllegalArgumentException("fib is not applicable to $n")
    n == 0, n == 1 -> 1
    else -> fibMemo.getOrPut(n) { fibN(n - 1) + fibN(n - 2) }
}

The easiest way is to use a null check 最简单的方法是使用空检查

var a : Int? = 12
var b : Int      
b = a // error!
b = if(a != null) a else -1    //automatic typecast from Int? to Int

You can refer more about null-safe Type casts over here : Null Safety - Kotlin 你可以在这里详细介绍零安全类型转换: Null Safety - Kotlin

In addition to checking for the presence of the key, you will also need to ensure that the returned value is not null as java.util.HashMap allows null values. 除了检查密钥是否存在外,还需要确保返回的值不为null因为java.util.HashMap允许null值。

You can do that by either surrounding your call to get with an explicit null check or by invoking !! 你可以做到这一点无论是周围的您的来电get具有显式null支票或通过调用!! on the returned value. 在返回的值上。

Your workaround to use as Int will be flagged as an unsafe cast warning by IDEA, and therefore is not advisable. as Int变通方法将被IDEA标记为不安全的强制转换警告,因此不建议。

The short answer is you can't unless you emphatically state to the compiler that the nullable int can't and won't be null through the use of two exclamation marks or through the use of an if statement ; 简短的回答是你不能,除非你强烈地告诉编译器, nullable int不能通过使用两个感叹号或通过使用if statement而为null ; because int is a subtype of int? 因为intintsubtype int?

Here is an example. 这是一个例子。

val x:Int? = 1
val y: Int =2

x=y // No error
y=x // Error
y=x!! // No error

您还可以在null情况下使用默认值:

val int: Int val nullableInt: Int? = null int = nullableInt ?: 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM