呼ぶといなくなる関数
概要
呼ぶとそれ自身がいなくなるような関数はないものかと一考。
object SelfErase { var f : () => Unit = {() => f = null} var g = {() => val field = getClass().getDeclaredField("g") field.setAccessible(true) field.set(this, null)} def main(args : Array[String]) : Unit = { //doesn't compile // var h : () => Unit = {() => h = null} println(f == null) //f erase f itself f() println(f == null) println(g == null) //g erase g itself g() println(g == null) var h : (() => Unit) => Unit = {f2 => f2()} println(h == null) h({() => h = null}) println(h == null) } }
あっさりできた。(f)
リフレクションでもできた。(g)
JavaVMからみるとgはprivateだったのでfield.setAccessible(true)で対応。
ローカル変数ではできなさそうだった。
(前方参照だ、とか言われる)
(h)はhの中からh = nullを呼べていないので違う気がする。