みなさん Kotlin は書いていますか?僕は、最近書き始めました🧑🔧 Swift との構文の違いを比較しながら勉強していくのが、結構楽しくてハマっています🎣
今回はそんな Kotlin で使用する型などを簡単にまとめてみたいと思います。
基本の型
まずは、Kotlin Language の Basic Type にも記載されていたここに注目してみます。
In Kotlin, everything is an object in the sense that we can call member functions and properties on any variable.
Kotlin では、メンバ関数やプロパティなどをどのような変数からでも呼び出せるように全てのものがオブジェクトとして作られています。つまり、提供されている型は全て参照型ということが言えそうで、Swift の Basic Type とは異なります🤔 以前に、Swift の Class と Struct
の記事でも記載した通り、Swift の基本的な型の多くは値型として提供されています。
ちなみに Kotlin と Swift それぞれの整数値(Int) の実装をちょこっと下記に載せておきます。
Kotlin - Int:
public class Int private constructor() : Number(), Comparable<Int> { companion object { /** * A constant holding the minimum value an instance of Int can have. */ public const val MIN_VALUE: Int = -2147483648 /** * A constant holding the maximum value an instance of Int can have. */ public const val MAX_VALUE: Int = 2147483647 /** * The number of bytes used to represent an instance of Int in a binary form. */ @SinceKotlin("1.3") public const val SIZE_BYTES: Int = 4 /** * The number of bits used to represent an instance of Int in a binary form. */ @SinceKotlin("1.3") public const val SIZE_BITS: Int = 32 }
Swift - Int:
@frozen public struct Int : FixedWidthInteger, SignedInteger { /// A type that represents an integer literal. public typealias IntegerLiteralType = Int /// Creates a new instance with the same memory representation as the given /// value. /// /// This initializer does not perform any range or overflow checking. The /// resulting instance may not have the same numeric value as /// `bitPattern`---it is only guaranteed to use the same pattern of bits in /// its binary representation. /// /// - Parameter x: A value to use as the source of the new instance's binary /// representation. public init(bitPattern x: UInt)
ということで、下記が基本的なタイプになります。
型 | 内容 |
---|---|
Double | 64ビット浮動小数点 |
Float | 32ビット浮動小数点 |
Long | 64ビット整数 |
Int | 32ビット整数 |
Short | 16ビット整数 |
Byte | 8ビット整数 |
Boolean | 真偽 |
Char | 文字 |
String | 文字列 |
Array | 配列 |
また、この他にも Swift などでもお馴染みの Any型などもあります。
リテラル定数
整数値のリテラル定数:
整数値のデフォルトリテラルは Int型になります。
123
-> Int123L
-> Long- 末尾に
L
でタグをつけるとLong
型になります。
- 末尾に
0x0F
16進数0b00001011
2進数
浮動小数点のデフォルトリテラルは Double 型になります。
123.5
、123.5e10
-> Double123.4f
-> Float- 末尾に
f
もしくはF
タグをつけるとFloat
型になります。
- 末尾に
今回はここまでにして、また次回 Kotlin の型について深堀していきたいと思います。では、また明日🧑🔧
参考
- https://kotlinlang.org/docs/reference/basic-types.html#basic-types
- https://qiita.com/AAkira/items/16ae2e9c0f6073e0e983
- https://ikuty.com/2018/11/30/kotlin_basic_syntax_type/