官术网_书友最值得收藏!

Numbers

Basic Kotlin data types used for numbers are equivalents of Java numeric primitives:

Kotlin, however, handles numbers a little bit differently than Java. The first difference is that there are no implicit conversions for numbers--smaller types are not implicitly converted to bigger types:

    var weight : Int = 12 
    var truckWeight: Long = weight // Error1 

This means that we cannot assign a value of type Int to the Long variable without an explicit conversion. As we said, in Kotlin everything is an object, so we can call the method and explicitly convert the Int type to Long to fix the problem:

    var weight:I nt = 12 
    var truckWeight: Long = weight.toLong() 

At first, this may seem like boilerplate code, but in practice this will allow us to avoid many errors related to number conversion and save a lot of debugging time. This is actually a rare example where Kotlin syntax has more code than Java. The Kotlin standard library supports the following conversion methods for numbers:

  • toByte(): Byte
  • toShort(): Short
  • toInt(): Int
  • toLong(): Long
  • toFloat(): Float
  • toDouble(): Double
  • toChar(): Char

We can, however, explicitly specify a number literal to change the inferred variable type:

    val a: Int = 1 
    val b = a + 1 // Inferred type is Int 
    val b = a + 1L // Inferred type is Long

The second difference between Kotlin and Java with numbers is that number literals are slightly different in some cases. There are the following kinds of literal constants for integral values:

    27 // Decimals by default 
    27L // Longs are tagged by a upper case L suffix 
    0x1B // Hexadecimals are tagged by 0x prefix 
    0b11011 // Binaries are tagged by 0b prefix 

Octal literals are not supported. Kotlin also supports a conventional notation for floating-point numbers:

    27.5 // Inferred type is Double 
    27.5F // Inferred type is Float. Float are tagged by f or F 
主站蜘蛛池模板: 花莲市| 托克逊县| 文成县| 邮箱| 开封县| 新乡市| 通榆县| 于都县| 甘肃省| 台前县| 玉环县| 安宁市| 新竹市| 改则县| 汾西县| 电白县| 怀柔区| 铜山县| 田林县| 密云县| 额尔古纳市| 南开区| 南宁市| 鹤峰县| 鄱阳县| 建湖县| 九江市| 遵义县| 鲁甸县| 博罗县| 卢湾区| 大庆市| 东宁县| 武安市| 长寿区| 光山县| 大田县| 泰顺县| 长泰县| 慈溪市| 翁牛特旗|