iOSエンジニアのつぶやき

毎朝8:30に iOS 関連の技術について1つぶやいています。まれに釣りについてつぶやく可能性があります。

Kotlin の型について知ろう

みなさん Kotlin は書いていますか?僕は、最近書き始めました🧑‍🔧 Swift との構文の違いを比較しながら勉強していくのが、結構楽しくてハマっています🎣

今回はそんな Kotlin で使用する型などを簡単にまとめてみたいと思います。

基本の型

まずは、Kotlin Language の Basic Type にも記載されていたここに注目してみます。

kotlinlang.org

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 の基本的な型の多くは値型として提供されています。

yamato8010.hatenablog.com

ちなみに 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 -> Int
  • 123L -> Long
    • 末尾に L でタグをつけると Long 型になります。
  • 0x0F 16進数
  • 0b00001011 2進数

浮動小数点のリテラル定数:

浮動小数点のデフォルトリテラルは Double 型になります。

  • 123.5123.5e10 -> Double
  • 123.4f -> Float
    • 末尾に f もしくは F タグをつけると Float 型になります。

今回はここまでにして、また次回 Kotlin の型について深堀していきたいと思います。では、また明日🧑‍🔧

参考

その他の記事

yamato8010.hatenablog.com

yamato8010.hatenablog.com

yamato8010.hatenablog.com