- Android Development with Kotlin
- Marcin Moskala Igor Wojda
- 320字
- 2021-07-02 18:48:36
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
- 企業級Java EE架構設計精深實踐
- Debian 7:System Administration Best Practices
- Apache Spark 2 for Beginners
- Visual C++串口通信技術詳解(第2版)
- 前端架構:從入門到微前端
- 高級C/C++編譯技術(典藏版)
- Microsoft Dynamics GP 2013 Reporting, Second Edition
- Hands-On RESTful Web Services with Go
- WebRTC技術詳解:從0到1構建多人視頻會議系統
- SQL經典實例(第2版)
- ASP.NET Core 2 Fundamentals
- TypeScript圖形渲染實戰:2D架構設計與實現
- 例說FPGA:可直接用于工程項目的第一手經驗
- Visual Basic語言程序設計上機指導與練習(第3版)
- SAP HANA Cookbook