I have the following code:
abstract class AList {
def head:Int
def tail:AList
def isEmpty:Boolean
def ::(n: Int): AList = SimpleList(n, Empty)
}
object Empty extends AList {
def head = throw new Exception("Undefined")
def tail = throw new Exception("Undefined")
def isEmpty = true
}
case class SimpleList(head: Int, tail: AList = Empty) extends AList {
def isEmpty = false
}
1 :: 2 :: Empty
I wonder how the last line actually works. There is no implicit conversion from Int to SimpleList. Hence I do not understand the method call mechanism.
Object.method(Arg)
I do not see that pattern here. I think a clarification of Scala notation (infix, suffix, postfix, etc...) would help. I'd like to understand the syntactic sugar.
In Scala, method names ending with a colon..
So 1 :: 2 :: Empty
is actually Empty.::(2).::(1)
. .
::
is a method of the right operand. In scala if a method name ends in a colon the method is invoked on the right operand. So 1 :: 2 :: Empty
is actually Empty.::(2)
which returns a SimpleList
.
The subsequent 1 :: <the-new-simple-list>
is easy to follow once you understand that ::
is a method of the right operand.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.