Skip to content

Instantly share code, notes, and snippets.

@ohtsuchi
Last active September 30, 2017 19:42
Show Gist options
  • Save ohtsuchi/4f6d7ab6d6d84512cf54daac5b75fc5f to your computer and use it in GitHub Desktop.
Save ohtsuchi/4f6d7ab6d6d84512cf54daac5b75fc5f to your computer and use it in GitHub Desktop.
if else で返す値の型が違う場合 の 型推論 #read_kotlin
interface I1
interface I2
class A : I1, I2
class B : I1 // A と 共通の親が I1
class C : I1, I2 // A と 共通の親が I1, I2
fun main(args: Array<String>) {
// 共通の親が1つ(I1)ある場合はI1、共通の親が2つ(I1,I2)の場合はAnyに型推論される
val x = if (true) A() else B() // x: I1
val y = if (true) A() else C() // y: Any
val a: I1 = x
val b: I1 = y // Type mismatch: inferred type is Any but I1 was expected
val c: I2 = y // Type mismatch: inferred type is Any but I2 was expected
}
@ohtsuchi
Copy link
Author

ohtsuchi commented Sep 12, 2017

Kotlinスタートブック読書勉強会 #1 (#read_kotlin)

自分がいたテーブルで帰り際に話題になって、終了後に ツイートした 内容

  • if else で返す値の型が違う(AB, AC)場合 の 型推論
    • 共通の親が1つ(I1)ある場合はI1
    • 共通の親が2つ(I1,I2)の場合はAnyに 型推論される

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment