Created
March 19, 2014 10:41
-
-
Save gregakespret/9639260 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.example | |
abstract class Person(val name: String) | |
// cannot be case class, because case classes have all parameters as vals and it wouldn't make sense to lazily instantiate them | |
class Girl(val name2: String, _boyfriend: => Boy) extends Person(name2) { | |
lazy val boyfriend = _boyfriend | |
} | |
class Boy(val name2: String, _girlfriend: => Girl) extends Person(name2) { | |
lazy val girlfriend = _girlfriend | |
} | |
object Main extends App { | |
// this will work because it is at object/class level | |
val alice1: Girl = new Girl("alice", bob1) | |
val bob1 = new Boy("Bob", alice1) | |
println(alice1.boyfriend.girlfriend.name) | |
// this will not work because it is at block/scope level | |
// def method = { | |
// val alice: Girl = new Girl("alice", bob) <-- it will fail at this line with "forward reference extends over definition of value alice" | |
// val bob = new Boy("Bob", alice) | |
// println(alice.boyfriend.girlfriend.name) | |
// } | |
// this works if we make both of them lazy and they are both instantiated at println line, when the first one is needed | |
def method = { | |
lazy val alice: Girl = new Girl("alice", bob) | |
lazy val bob = new Boy("Bob", alice) | |
println(alice.boyfriend.girlfriend.name) | |
} | |
method | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment