Skip to content

Instantly share code, notes, and snippets.

@mather
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mather/7da72a40164eb8baf424 to your computer and use it in GitHub Desktop.
Save mather/7da72a40164eb8baf424 to your computer and use it in GitHub Desktop.
Scalaのトレイトで抽象メンバとそれを参照する`lazy val`のあるときに、`lazy val`を参照する側にも常に`lazy`であることを要求してしまう例
trait Hoge {
protected val hoge: String
lazy val l = hoge.length
}
trait Piyo {
this: Hoge =>
val p = l
}
class Fuga1 extends Piyo with Hoge {
override protected val hoge: String = "HOGE"
}
val f1 = new Fuga1
// java.lang.NullPointerException
// at Hoge$class.l(<console>:10)
// at Fuga.l$lzycompute(<console>:12)
// at Fuga.l(<console>:12)
// at Piyo$class.$init$(<console>:11)
// ... 34 elided
trait LazyPiyo {
this: Hoge =>
lazy val p = l
}
class Fuga2 extends LazyPiyo with Hoge {
override protected val hoge: String = "HOGE"
}
val f2 = new Fuga2
f2.p //=> 4
// あるいは事前定義をする
class Fuga3 extends {
protected val hoge: String = "HOGE"
} with Piyo with Hoge
val f3 = new Fuga3
f3.p //=> 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment