LoginSignup
10
9

More than 5 years have passed since last update.

scala の repl で手軽に構文糖を解く(desugarする)

Last updated at Posted at 2017-03-06

普段使わないので使おうと思った時に思い出せないアレ。

1. 行末に // print + タブ

例: for式ってどう展開されるんだったかな?

scala> for (i <- Option(1)) yield i // print
   scala.Option.apply[Int](1).map[Int](((i: Int) => i)) // : Option[Int]

// print の後にタブを押すと2行目が表示される。この場合の for 式は map() に展開されることが分かる。

//print + タブ は代入文には使えないようだ。 val x = 1 + 1 // print と入力してタブを押しても何も表示されない。他にも使えないパターンがあるかもしれない。

2. 行末に // show で評価(Enter)

こちらは評価する前に desugar された状態のプログラムが表示される。
周りの object も表示されるのが少し煩い。

scala> for (i <- Option(1)) yield i // show
object $read extends scala.AnyRef {
  def <init>() = {
    super.<init>;
    ()
  };
  object $iw extends scala.AnyRef {
    def <init>() = {
      super.<init>;
      ()
    };
    object $iw extends scala.AnyRef {
      def <init>() = {
        super.<init>;
        ()
      };
      val res3 = Option(1).map(((i) => i))
    }
  }
}
res3: Option[Int] = Some(1)

// print + タブと違い代入文でもいけるようだ。

scala> val x = 1 + 1 // show
object $read extends scala.AnyRef {
  def <init>() = {
    super.<init>;
    ()
  };
  object $iw extends scala.AnyRef {
    def <init>() = {
      super.<init>;
      ()
    };
    object $iw extends scala.AnyRef {
      def <init>() = {
        super.<init>;
        ()
      };
      val x = 1.+(1)
    }
  }
}
x: Int = 2
10
9
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
9