heihei blog

Writing for myself!📝

Notes - Kotlin Types: Exposed by Svetlana Isakova (KotlinConf 2017)

※Notes記事では、英語のセッション動画やポッドキャストの内容を(雑に)英語でメモに書き残すことを行っています。 本記事は、あくまで動画を見ながら、参考程度に読んでいただくことを想定しています。これから動画を見る方にとって本記事の内容が少しでもお役に立てば幸いです。(内容において不備、誤字脱字等ありましたらご連絡いただければと思います。)

本記事はKotlin Types: Exposed by Svetlana Isakova (KotlinConf 2017)の記事です。



  • Basic Types
  • Nullable types
  • Collection types

How those types interact with Java and what happens when we mix types of Kotlin and Java

fun foo(): Int = 1

fun bar(): Int? = 1
public static final int foo() {
  return 1;

public static final Integer bar() {
  return Integer.of(1);

If you want to know what is going on under the food, you can "show kotlin bytecode" (and also decompile the byte code) in Android Studio

Correspondence between Kotlin and Java types

  • Int in Kotlin => int in Java
  • Int? in Kotlin => java.lang.Integer in Java

Kotlin does not have Primitive types in the language, yet Kotlin still has Primitive types in the byte code level by making use of wrapper types and nullable types

Generic arguments

  • List<Int> in Kotlin => List<Integer> in Java
  • Array<Int> in Kotlin => Integer[] in Java
Arrays of primiteve types

If you want to use primitive types of array, then use IntArray in Kotlin: - IntArray in Kotlin => int[] in Java


kotlin.String in Kotlin => java.lang.String in Java

kotlin.String hides some confusing methods:

e.g. replaceAll method

In Java:

"one.two.".replaceAll(".", "*") => *******

In Kotlin:

"one.two.".replace(".", "*") => one*two

"one.two.".replace(".".toRegex(), "*") => one*two


  • Any in Kotlin => java.lang.Object in Java
  • Any type is the super type for ALL types, including Int or anything
Boxing under the hood
log(2017) // the value is autoboxed

fun log(any: Any) {
  println("Value: $any")

fun log(i: Int) {
  println("Value: $i")

Unit (Kotlin) vs Nothing (Kotlin) vs void (Java)?

The concept comes from functional programming; from the Type system

  • Unit: "a type that allows only one value and thus can hold no information" => The function completes
  • Nothing: "a type that has no values" => The function never completes
Unit instead of void

Whenever you use void in Java, you use Unit in Kotlin


  • No meaningful value is returned
  • No explicit returned type implies you return Unit by default
  • Two equivalent syntactic forms:
fun f() { /*…*/ }

fun f(): Unit { /*…*/ }

Under the hood, Unit is still void in the byte code

Nothing is different to Unit/void

Unit and Nothing are two very different types even though in the byte code level both mean void type

  • Nothing means "this function never returns"
Any & Nothing types
  • Any is a super type for all the other types
  • Nothing is a subtype for all the other types

e.g. fail function below returns Unit

val answer = if (timeHasPassed()) {
} else {
  fail("Not ready")

fun fail(message: String) {
  throw IllegalStateException(message)
  • If 42 is returned then the returned type of the expression function is Int
  • If fail function is called then the returned type of the expression function is Unit

=> Kotlin compiler thinks that the expression function returns Any type because the super type of both Int and Unit is Any

Returning Any means the variable answer will be initialized even if it fails, which is not what we expect; we expect it not to be initialized when it fails. => We can use Nothing in this case

Nothing is a subtype for all the other types, so that means the returned type of the expression function is now Int, which is what we expect

Type of null

var user = null // => var user: Nothing? = null
user = User("svtk") // Error: Type mismatch

val users = mutableListOf(null) // => var users: List<Nothing?> = mutableListOf(null)
users.add(User("svtk")) // Error: Type mismatch

Nullable types & Java

Nullable Types Under the Hood => Just annotations

If your returned type is annotated with @Nullable in Java, then in Kotlin, the type will become nullable

How to still prevent NPEs?

  • Annotate your Java types
    • @Nullable type
    • @NotNull type

Non-null by default (JSR-305):

@TypeQualifierDefault(ElementType.PARAMETER, …)
annotation class MyNonnullByDefault


  package mypackage;

Then, Kotlin will give you warning when assigning null to values:

public class Session {
  public void setDescription(String description) {
    this.description = description;

Calling Java code from Kotlin:

val session = Session()
session.setDescription(null) // => Warning: Expected type doesn't accept nulls in Java …

If you prefer errors in compile time rather than warnings:


compileKotlin {
  kotlinOptions {
    freeCompilerArgs += "-Xjsr305=strict"

Then, Kotlin will give you errors when assigning null to values:

public class Session {
  public void setDescription(String description) {
    this.description = description;

Calling Java code from Kotlin:

val session = Session()
session.setDescription(null) // => Error: Null can not be a value of a non-null type …


  • Specify types explicitly
public class Session {
  public void setDescription(String description) {
    this.description = description;
val session = Session()
val description: String? = session.description ✅

Or, the code below gives you IllegalStateException in runtime which notifies you very early what is wrong with your code:

val session = Session()
val description: String = session.description // IllegalStateException: session.description must not be null

How it works? - Intrinsic checks

The code below will be generated by compiler:



Read-only interfaces improve API

  • How read-only collections and mutable collections work in Kotlin

List & MutableList

  • Two interfaces declared in kotlin package
  • MutableList extends List

Read-only DOES NOT mean immutable - Read-only interface just lacks mutating methods

The actual list can be changed by another reference:

val mutableList = mutableListOf(1, 2, 3)
val list: List<Int> = mutableList

println(list) // [1, 2, 3]

println(list) // [1, 2, 3, 4]

In Kotlin, there is a plan to provide the immutable data structure in the standard library, but it is not ready yet

  • String! = notation, not syntax; platform type, which is a type that comes from Java

Platform types: summary

Good compromise between safety and convenience


  • primitives under the hood, and boxing is possible
  • Use Nothing whenever possible
  • Preventing NPE for Java interop: annotations, explicit types
  • Read-only does not mean immutable


Notes - Fragmented Podcast: 105: Jake Wharton on the Android Kotlin Guides


本記事は、Fragmented Podcast: 105: Jake Wharton on the Android Kotlin Guidesの記事です。



  • Jake Wharton working on android/kotlin-guides on github
    • Influenced by Google Java style guide
    • Hosting on GitHub makes it easy for people to not only access but also contribute
    • Different from JetBrains' style guide; following this style guide has no conflict with following JetBrains' style guide, but may not be vice-versa
  • Style guide to provide a set of rules to follow, and Interop guide to provide practices and things to care for those developers who ..
    • Introduce Kotlin into existing Java project
    • Consume Kotlin code from Java
    • Provide APIs in Kotlin that may be consumed from Java

105: Jake Wharton on the Android Kotlin Guides http://fragmentedpodcast.com/episodes/105/

About android/kotlin-guides

Q. Is this the defacto style guide for Kotlin? What was the reason for it?

There are two guides: Style guide and Interop guide

  1. Style guide for regular Android app developers to style..
    • code structure, and
    • new Kotlin files
  2. Interop guide for developers to easily co-exist both Kotlin and Java code without feeling awkward especially when calling codes from one language to the other.


  • Android has never had a style guide for non-Google developers
  • There was AOSP style guide but it was only for developers of ASOP. And, Android has been around for 10 years; Most apps have Java code so there needs to be something that people can follow to feel natural when introducing Kotlin code into existing Java code base or consuming APIs of Kotlin language from Java code base.

Q. Why NOT Google Kotlin Guide, and Android specific?

  • Currently Google makes use of Kotlin language for Android platform, so we want something tailored for it, fairly quickly, rather than something very general.
  • It is influenced by Google Java style guide

Q. What about current JetBrains' style guide?

android/kotlin-guides is consciously made not to have conflict with the guide from JetBrains. However, following JetBrains' Kotlin style guide does not mean it is 100% valid for android/kotlin-guides because JetBrains' kotlin-guide is more focused on Kotlin language itself and its future, but android/kotlin-guides cares about natural, comfortable interaction between Java and Kotlin languages as well.

IntelliJ platform does not support code formatting exactly as style guide recommends. (Information from KotlinConf)

Q. How did you start making android/kotlin-gudes?

Goal: - Easy to access - Easy to contribute

Docs on android.developer.com are difficult to contribute for developers.

  • Started with Google doc -> internal review -> API counsel ..etc.. Eventually to github.com with Jekyll

Q. How did you decide what to put in kotlin-guides, especially controversial ones as personal preference or something with non-logical reasons?

  • Looking up
  • Feedback from people from JetBrains who are making their guide in parallel

Q. One of the difficult choices? - for example, 2 spaces -> 1 tab(4 spaces)

  • Google Java style guide specify 2 spaces
  • JetBrains' kotlin guide specifies 1 tab
  • The almost all codebase at Square was also 2 spaces when Jake joined
  • "It seems everything is so far a part"

Q. Why "Style Guide" and "Interop Guide"?

Style Guide

Style guide aims to have rules that are unambiguous and can potentially be enforced or even formatted by an automated tool. - Meant to be 'Hard rules' - Everything should be deterministic, unambiguous just single way of doing something

Interop Guide

  • 'Rules but a bit of interpretation'
  • Something you need to think a bit
  • For people to have mixed (Java & Kotlin) sources

Eventually adding something more subjective.. - Design patterns - Best practices or patterns - Something people can decide whether or not they apply

Highlights of the guides

Style guide: Use-Site Targets

Style guide: Logical Ordering

Q. What is a good logical ordering?

  • The most important part of the guide is there is no "One true order"
  • The rule here is that "there is no rule"
  • Too strict ordering may harm the ability to understand what is going on.

Q. Why is the column limit 100 characters?

  • It is already being used
  • It is what Google Java style guide is using too
  • It is not considered as something that needs to be changed

Q. About "Higher syntactic level"

  • Stolen from Java style guide
  • When performing line breaking, you do not want to break
  • If you perform line breaking, you want to keep the inner function calls and their arguments together

Q. Expression Functions

  • Sometimes it is easier to have normal function body that have multiple expression bodies
  • By having expression functions it is tempting to delcare all functions as expression functions but sometimes it makes harder to read or understand the body of the function.

For contribution

The reason the guide is on GitHub is because we want people to contribute If there is ambiguity, wording miss, incorrect or not conveying the right thing please please contribute. - Already bunch of fixes and so on - Contents from KotlinConf - Thinking to release once every 2 or 3 weeks until the guide stabilizes - Do not want to overwhelm people with changes - Going to provide change logs to easily figure out what is changes

Use of annotations recommended by the style guide

  • You don't have to follow the every single rules but if you start writing codes from the scratch

Q. Do we / should we use Hungarian notations?

  • The language itself actively discourages you from using any kind of prefix.

e.g. Kotlin property delcaration which is consumed from Java

val mName: String = ...
pubic String getMName() { // Super weird!
    return ...;

Q. Interop Guide

Java (for Kotlin consumption)

The motivating factor here is that every new API that is added to Android Framework itself or support libraries are consumed from both languages by developers, so there is a strong need to have a set of rules that you can follow or interpret when you are writing these APIs to make sure that they actually feels nice from both languages.

Kotlin (for Java consumption)

We assume that in the near future, more libraries will be written in Kotlin first and those APIs may be consumed from people using Java, so the API Kotlin code needs to be feel idiomatic for them as well. That is the rason why there is a separation.

About "No hard keyword"

  • Kotlin has a notion of both "hard" and "soft" keyword
    • class
    • if
    • else
    • try
    • class
    • when

For example, You can't name a class 'name' or 'if'.

  • Keywords for Kotlin uses are different from keywords for Java uses.
  • If you were to write a new API the style guide strongly recommends not to use those keywords.

Q. Defensive copies

  • Kotlin does have a notion of 'read only' property
  • 2 parts of this: val(= read only), two versions of Collections

Whenever you return a list in a public API where you are sure or there is a possibility that the value will be refenced from Java then it should wrap it or make a defensive copy from Java

  • Guava has it's own version of immutable list
  • JetBrains is also working on Kotlinx.collection.immutable.





  • サービスを利用していて困ったことや欲しい機能があったらサポートに連絡してみましょう。
  • Firebaseのサポートは返信が丁寧です。(返信スピードが早い・更新情報があればその都度連絡してくれるので返信頻度が良い意味で多いです。)
  • (Firebaseに限っては)Firebaseサポートからフィードバックや機能リクエストを送ることができます。




元々FirebaseはFirebase, Inc.が独自に開発していたツールだったのですが、2014年の10月にGoogleが買収しました。(Google I/O 2015や2016, 2017年では多くのFirebaseに関するセッションがありました。)また、2017年1月にはTwitterがGoogleにFabricを売却したことも発表され、その後FabricからFirebase Crash Reportingへの移行も推奨されています。(自分はまだできていません..)




返信メールがその日のうちに返信メールが返ってきてとにかくフィードバックが早いなという印象でした。 自分の場合は、今後サポート予定ですでにスケジュールに組まれているのか、サポート予定だけど実装スケジュールは未定なのか、今のところサポート予定ではない、等を教えていただくことができました。必ずしも自分がリクエストした機能がサポートされるとは限りませんが、上記のようなスケジュール感を共有してもらえるのは開発者としてもありがたいです。










業務で開発・運用しているアプリケーションでは、Realtime Database, Authentication, Cloud Messagingを利用しています。


"XXX is a boxed field but needs to be un-boxed to execute YYY. This may cause NPE so Data Binding will safely unbox it. You can change the expression and explicitly wrap XXX with safeUnbox() to prevent the warning."の警告を見て、Data Binding周りを調べたことについて


  • Data Bindingライブラリで<data>タグと<variable>タグを利用してXML上に変数定義をする際には、プリミティブ型で定義できる際には積極的にプリミティブ型を使っていこう
  • 参照型の変数を定義した際には、Data Bindingライブラリが内部でunboxingする
  • safeUnbox()を利用することもできる



  • com.android.support:appcompat-v7: 27.0.1
  • com.android.databinding:compiler: 3.0.0

Data Bindingライブラリを使ってXML上に変数を定義してViewの見た目を変えるとします。下記は、isLoadingであればProgressBarを表示、そうでなければProgressBarを非表示(View.GONE指定)にする簡単なXMLの例です:

  <import type="android.view.View"/>
      android:visibility="@{isLoading ? View.VISIBLE : View.GONE}"






    type="android.view.View" />


w: 警告: XXX is a boxed field but needs to be un-boxed to execute YYY. This may cause NPE so Data Binding will safely unbox it. You can change the expression and explicitly wrap XXX with safeUnbox() to prevent the warning.

safeUnbox()というData Bindingライブラリが用意してくれているstaticメソッドを利用することもできるようです。

      android:visibility="@{safeUnbox(isLoading) ? View.VISIBLE : View.GONE}"


package android.databinding;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.databinding.BindingConversion;
@javax.annotation.Generated("Android Data Binding")
public class DynamicUtil {
    public static int safeUnbox(java.lang.Integer boxed) {
        return boxed == null ? 0 : (int)boxed;
    public static long safeUnbox(java.lang.Long boxed) {
        return boxed == null ? 0L : (long)boxed;
    public static short safeUnbox(java.lang.Short boxed) {
        return boxed == null ? 0 : (short)boxed;
    public static byte safeUnbox(java.lang.Byte boxed) {
        return boxed == null ? 0 : (byte)boxed;
    public static char safeUnbox(java.lang.Character boxed) {
        return boxed == null ? '\u0000' : (char)boxed;
    public static double safeUnbox(java.lang.Double boxed) {
        return boxed == null ? 0.0 : (double)boxed;
    public static float safeUnbox(java.lang.Float boxed) {
        return boxed == null ? 0f : (float)boxed;
    public static boolean safeUnbox(java.lang.Boolean boxed) {
        return boxed == null ? false : (boolean)boxed;

ただ、実際にはこのメソッド呼び出しをXML上で明示的に行わなくても、Data Bindingライブラリが生成するJavaのソースコード(下記)内でこのメソッドを呼び出して安全にunboxしてくれているようなので、これに関しては書いても書かなくてもどちらでも良さそうです。(詳しいことはしっかりとは調べれていませんので、言い切る自信はないですが)

// read android.databinding.DynamicUtil.safeUnbox(isLoading)
androidDatabindingDynamicUtilSafeUnboxIsLoading = android.databinding.DynamicUtil.safeUnbox(isLoading);











  • カンファレンス開催日
  • カンファレンス名
  • カンファレンス開催地
  • カンファレンス
  • 発表申込を受付中かどうか

上記レポジトリは世界中のAndroidアプリケーション開発者やカンファレンス主催者のPull Requestによって更新されています。 また、Call For Papers期間中(発表申込を受付中)の場合にはそれもひと目でわかるように緑のラベルのようなものがつけられていて親切です。






  1. 自動変換コードは常に疑う
  2. デコンパイルされたバイトコードのレビューをする

尚、内容はYahoo JAPAN!様で開催されたBonfire#2にて発表したものから抜粋しています。(発表資料はこの記事の下部にあります)


1. 自動変換を信用しすぎていたこと

Android Studioを用いたAndroidアプリケーション開発において、JavaのソースコードをKotlinに置き換える際には、自動変換のツールが用意されています。


⌘ Option Shift K







override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
  super.onActivityResult(requestCode, resultCode, data)



override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
  super.onActivityResult(requestCode, resultCode, data)

自動変換が便利で、ある程度信用しきっていた部分があったため、自分の場合この問題に出くわして( ゚д゚)ハッ!としました。何度も書きますが、自動変換は常に疑いましょう。手直しは必ず必要です。

2. (デコンパイルされたバイト)コードレビューをしていなかったこと

Javaにおけるstaticな定数をKotlinで定義したい場合にはcompanion objectを利用できます。

companion object {
  val SOME_VALUE = 1


public static final int SOME_VALUE = 1;
public static final class Companion {
  public final int getSOME_VALUE() {
    return MainActivity.SOME_VALUE;

String var2 = "" + Companion.getSOME_VALUE();


Kotlinでは、プロパティに対してデフォルトでsetter / getterが定義可能であれば定義される仕組みとなっています。

たとえばあるクラス内にvar someValue = 1というプロパティを定義した場合、KotlinではsetSomeValue()とgetSomeValue()メソッドが新たに生成されます。



  1. String型もしくはプリミティブ型のプロパティ: const val定義
  2. 1.以外のプロパティ: @JvmFieldアノテーション付与


1. String型もしくはプリミティブ型のプロパティ: const val定義


companion object {
  const val SOME_VALUE = 1


public static final int SOME_VALUE = 1;
public static final class Companion {

String var2 = "1";


2. @JvmFieldアノテーション付与




世の中では「Kotlinかわいい😍」というツイートをよく見かけますが、Null許容を表す一文字の?をつけるのか、そうでないのかによって大きな違いが生まれるのがKotlinです。怖いでしょ!?Javaでよくない!?とKotlinを否定しているのではありません。僕も思います!Kotlinかわいいです😍 !


Kotlinの良さに気づいた時、「Kotlinかわいい😍 」と目が♡になってしまい盲目になりKotlinに噛まれることのないよう、特にこれからJavaのソースコードをKotlinに置き換えていく方に向けて、下記の二点をオススメします:

  1. 自動変換を行う際には常に変換後のコードをチェック
  2. 可能であればバイトコードをデコンパイルしてレビュー

最後に、下記は、Yahoo! JAPAN Bonfire#2での登壇資料です。上記内容以外に自分がハマったこと等についていくつか紹介しています:

おまけ: 来年2月に開催されるDroidKaigiにて、fluxについて発表します。初の30分という長い時間と英語のプレゼンなので緊張しますが、選ばれたからにはしっかりやろうと思います!


AS3.0-stable + RobolectricによるUnitテストでResourceNotFoundExceptionが出る際の対策





app/build.gradleのandroid {}内にtestOptionsを追加し、Unitテスト実行時の設定を記述します。

testOptions {
  unitTests {
    includeAndroidResources = true

includeAndroidResourcesに関するドキュメントは下記です: UnitTestOptions - Android Plugin 3.0.0-dev DSL Reference





    at android.net.LocalSocketImpl.bind(LocalSocketImpl.java:303)
    at android.net.LocalServerSocket.__constructor__(LocalServerSocket.java:48)
    at android.net.LocalServerSocket.<init>(LocalServerSocket.java)
    at com.facebook.stetho.server.LocalSocketServer.bindToSocket(LocalSocketServer.java:142)
    at com.facebook.stetho.server.LocalSocketServer.listenOnAddress(LocalSocketServer.java:78)
    at com.facebook.stetho.server.LocalSocketServer.run(LocalSocketServer.java:74)
    at com.facebook.stetho.server.ServerManager$1.run(ServerManager.java:40)


IllegalStateException: TZDB.dat missing from assets


参考: IllegalStateException: TZDB.dat missing from assets · Issue #24 · JakeWharton/ThreeTenABP · GitHub