第41回 そろそろ、Kotlin?
ふと、手にした本が、Kotlin書だったために、ブログの更新も忘れて、読みふけってました。
Kotlin使って見たいけど、Kotlinの情報は少ない。
私にとってもメリットは、javaーswift の差よりも、kotlinーswiftの差の方が近いのではというその一点だけだったのですが。
例えば、
swift (変数名):(変数の型)
java (変数の型) (変数名)
kotlin(変数名):(変数の型)
ご覧のように、javaだけが反対なんですから。
次のようなjavaファイルをそのまま、kotlinファイルにコピペしてみました。
class MySize { // このクラスにはいろいろなビューのサイズを保管する //基本の画面サイズ public static int screenWidth; public static int screenHeight; // 初期化の必要なのはこの2つだけ public static void setWidth(int width) { screenWidth = width; } public static void setHeight(int height) { screenHeight = height; } // 各種パーツの長さ // 文字サイズ // TypedValue.COMPLEX_UNIT_PX で指定する public static class TextSize { // テキストサイズ static float normal = (float) screenWidth * 0.08f; static float small = (float) screenWidth * 0.05f; }
ペーストの直後、kotlinに変換しますか?みたいなメッセージが出て、そのままOKするとできたのが、次のファイル。
internal object MySize { // このクラスにはいろいろなビューのサイズを保管する //基本の画面サイズ var screenWidth: Int = 0 var screenHeight: Int = 0 // 初期化の必要なのはこの2つだけ fun setWidth(width: Int) { screenWidth = width } fun setHeight(height: Int) { screenHeight = height } // 各種パーツの長さ // 文字サイズ // TypedValue.COMPLEX_UNIT_PX で指定する object TextSize { // テキストサイズ internal var normal = screenWidth.toFloat() * 0.08f internal var small = screenWidth.toFloat() * 0.05f } // アプリ共通の線幅 object LineWidth { // 線幅 internal var normal = screenWidth / 100 internal var thin = screenWidth / 150 internal var thich = screenWidth / 80 }
何がわかったかというと、javaではスタティックなクラスしか使えなかったのが、親切な変換をしてもらったら、classからobjectに変わってた。
static もきれいに排除されています。
で、よくよく、object構文を見てみると、もしかして、swiftのstructに当たるのでは?と思い始めたわけなんです。
swiftのstructは使ったことないです。解説を読んでみると、class も struct もインスタンスを作ることができるそうです。だから、structなくてもプログラム組めるじゃんって、無視してきました。でも、swift-structはもしかしたら、staticなクラスから、構造体への置き換えで使えるんじゃって思って、今、色々実験中です。案外うまくいくかもしれません。しばらくは、Kotlin でこんなことできた、こんなことしたよって、記事を書いてみたいと思います。