📜  Kotlin 类型转换

📅  最后修改于: 2022-05-13 01:54:41.022000             🧑  作者: Mango

Kotlin 类型转换

类型转换(也称为类型转换)是指将一种数据类型变量的实体转换为另一种数据类型。正如我们所知, Java支持从较小数据类型到较大数据类型的隐式类型转换。可以将整数值分配给 long 数据类型。例如:

Java
public class TypecastingExample { 
   public static void main(String args[]) { 
      byte p = 12; 
      System.out.println("byte value : "+p); 
                                                  // Implicit Typecasting 
      long q = p;                                  // integer value can be assigned
                                                 // to long data type   
   }
 }


Kotlin
fun main(args: Array)
{
    println("259 to byte: " + (259.toByte()))
    println("50000 to short: " + (50000.toShort()))
    println("21474847499 to Int: " + (21474847499.toInt()))
    println("10L to Int: " + (10L.toInt()))
    println("22.54 to Int: " + (22.54.toInt()))
    println("22 to float: " + (22.toFloat()))
    println("65 to char: " + (65.toChar()))
    println("A to Int: " + ('A'.toInt()))
}


但是,Kotlin 不支持隐式类型转换。整数值不能分配给 long 数据类型。

var myNumber = 100
var myLongNumber: Long = myNumber       // Compiler error
// Type mismatch: inferred type is Int but Long was expected

在 Kotlin 中,辅助函数可用于将一种数据类型显式转换为另一种数据类型。

例子:

var myNumber = 100
var myLongNumber: Long = myNumber.toLong()     // compiles successfully

以下帮助函数可用于将一种数据类型转换为另一种数据类型:

  • toByte()
  • 太短()
  • toInt()
  • toLong()
  • 浮动()
  • toDouble()
  • toChar()

从较大的数据类型转换为较小的数据类型

var myLongNumber = 10L
var myNumber2: Int = myLongNumber1.toInt()

Kotlin 程序将一种数据类型转换为另一种数据类型:

科特林

fun main(args: Array)
{
    println("259 to byte: " + (259.toByte()))
    println("50000 to short: " + (50000.toShort()))
    println("21474847499 to Int: " + (21474847499.toInt()))
    println("10L to Int: " + (10L.toInt()))
    println("22.54 to Int: " + (22.54.toInt()))
    println("22 to float: " + (22.toFloat()))
    println("65 to char: " + (65.toChar()))
    println("A to Int: " + ('A'.toInt()))
}

输出:

259 to byte: 3
50000 to short: -15536
21474847499 to Int: 11019
10L to Int: 10
22.54 to Int: 22
22 to float: 22.0
65 to char: A
A to Int: 65