ちょっと Kotlinっぽく書き換えてみる
自動でコンバートした状態でも問題なく動きますが、実はテンプレートのファイルが古い?為に deprecated なメソッドを呼んでいる箇所があります。
45行目の getMap() です。
今は getMap() でなく、非同期だけど返ってくる GoogleMap が null にならない、getMapAsync() を使うことになっています。
というわけで、この部分とここから呼び出される setUpMap を少し書き換えてみました。
private fun setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the map. if (mMap == null) { // Try to obtain the map from the SupportMapFragment. (getSupportFragmentManager().findFragmentById(R.id.map) as SupportMapFragment) .getMapAsync({(googleMap:GoogleMap) -> setUpMap(googleMap)}) } } /** * This is where we can add markers or lines, add listeners or move the camera. In this case, we * just add a marker near Africa. * <p/> * This should only be called once and when we are sure that {@link #mMap} is not null. */ private fun setUpMap(googleMap: GoogleMap) { mMap = googleMap googleMap.addMarker(MarkerOptions().position(LatLng(0.0, 0.0)).title("Marker")) }
これで、deprecated なメソッドはなくなって、getMapAsync() の呼び出しも Javaっぽくなくなりました。
もちろん、動作も問題ありません。
(!!がどうにも嫌だったのでこんな書き方になってますが…)
というわけで、GoogleMapテンプレートで作った地図アプリを Kotlin にコンバートして動かしてみました。
基本的に”自動”でコンバートしてくれるので、特に難しいところはありません。
あとは、位置情報を取得したり、画面を書き換えたり、ジオフェンスでアラート出したりする部分をガシガシ kotlin で書いてみると、その良さをもっともっと感じられると思います。