In Kotlin, a numeric value of one type is not automatically converted to another type, even if the other type is larger.

So let’s define two variables: a int and assign it, and a long and assign a to b, so let’s say int and assign to long. Ok?

    var a:Int = 4
    var b:Long = a
Copy the code

The above code is marked red in the editor, indicating a type mismatch. I need to change the type of B from Long (64 bits) to Int (32 bits). When I replace the type, the error disappeared. As you can see from the editor’s code, a value of the lower type cannot be assigned to a variable of the higher type, but we can use the method provided by the object to display the conversion to raise the value of the lower type, such as Int to Long

    var a:Int = 4
    var b:Long = a.toLong()
Copy the code

This way, A can be assigned to B of type Long directly by calling toLong().

All of Kotlin’s numeric types provide to methods that convert each other

  • ToByte () – Parses a string into a number of signed bytes and returns the result.
  • ToShort () – Converts an Int value to a Short.
  • ToInt () – Parses a string to an Int number and returns the result.
  • ToLong () – Parses the string to a Long number and returns the result.
  • ToFloat () – Parses a string into a Float number and returns the result.
  • ToDouble () – Parses a string to a Double number and returns the result.
  • ToChar () – Converts an Int to a Char.

The ones above are low to high, but what about high to low?

Var a:Long = 4 var b:Int = a The editor also prompts that the Type does not match Kotlin: Type mismatch: inferred Type is Long but Int was expectedCopy the code

In fact, it can also be converted by the corresponding to method, but it is possible to truncate the value when converting from the high to the low, so that the value will change and cause errors. What if we convert an Int a=8888 Byte

var a: Int = 888 var b: Byte = a.toyte () println("a=" + a) println(" a.toyte () assigned to b=" + b) Input result: A =888 A.toyte () assigned toB =120Copy the code

When A converts, it changes from 888 to 120. This is the high switching to the low leading to truncation. If A is less than 120, this will not happen. The converted value has no possibility of truncation in the converted range

Boolean cannot convert to and from any type.

Automatic promotion

This is not to say that types cannot be automatically promoted, but there is a prerequisite for this, and the prerequisite is that the operator, when the type participates in the arithmetic operation, will perform the corresponding type promotion

  var a: Int = 888
  var b: Byte = 5
  var c:Int = a+b
Copy the code

B is converted when it sums with A, and the actual type of B does not change