What is the difference between Int and Integer in Kotlin?

后端 未结 3 507
遇见更好的自我
遇见更好的自我 2021-02-05 06:33

I have tried using Int and Integer types in Kotlin.Although I don\'t see any difference. Is there a difference between Int and Integer types in Kotlin?Or are they the same?

相关标签:
3条回答
  • 2021-02-05 07:33

    Just have a look at https://kotlinlang.org/docs/reference/basic-types.html#representation

    On the Java platform, numbers are physically stored as JVM primitive types, unless we need a nullable number reference (e.g. Int?) or generics are involved. In the latter cases numbers are boxed.

    That means, that Int is represented as primitive int. Only in cases when nullability or generics are involved, the backing Wrapper Type Integer must be used. If you use Integer from the beginning, you always work with the wrapper type and never with the primitive int.

    0 讨论(0)
  • 2021-02-05 07:36

    A Int is a primitive Type. This is equivalent to JVM int.

    A nullable Int Int? is a boxed Type. This is equivalent to java.lang.Integer.

    0 讨论(0)
  • 2021-02-05 07:39

    Int is a Kotlin Class derived from Number. See doc

    [Int] Represents a 32-bit signed integer. On the JVM, non-nullable values of this type are represented as values of the primitive type int.

    Integer is a Java Class.

    If you were to search the Kotlin spec for "Integer", there is no Kotlin Integer type.

    If you use the expression is Integer in IntelliJ, the IDE warns...

    This type shouldn't be used in Kotlin, use Int instead.

    Integer will interoperate well with Kotlin Int, but they do have some subtle differences in behavior, for example:

    val one: Integer = 1 // error: "The integer literal does not conform to the expected type Integer"
    val two: Integer = Integer(2) // compiles
    val three: Int = Int(3) // does not compile
    val four: Int = 4 // compiles
    

    In Java, there are times where you need to explicitly "box" an integer as an object. In Kotlin only Nullable integers (Int?) are boxed. Explicitly trying to box a non-nullable integer will give a compiler error:

    val three: Int = Int(3) // error: "Cannot access '<init>': it is private in 'Int'
    val four: Any = 4 // implicit boxing compiles (or is it really boxed?)
    

    But Int and Integer (java.lang.Integer) will be treated the same most of the time.

    when(four) {
        is Int -> println("is Int")
        is Integer -> println("is Integer")
        else -> println("is other")
    } //prints "is Int"
    when(four) {
        is Integer -> println("is Integer")
        is Int -> println("is Int")
        else -> println("is other")
    } //prints "is Integer"
    
    0 讨论(0)
提交回复
热议问题