问题描述:

for (i <- 0 to 1; c <- 0 until str.length) {

print(c + i).toChar

}

for (i <- 0 to 1; c <- 0 until str.length) yield (str(c) + i).toChar

When I run the first code snippet above I get the error: value toChar is not a member of Unit. But when I run the second code snippet with yield the error goes away.

Is this because the statement print(c+i) in the block statement in the first code snippet returns a value of Unit and the Unit datatype doesn't have a function called toChar? I am having a hard time figuring out when something returns Unit in a block statement in Scala.

网友答案:

This is because <fn>() -- function call operator has higher priority that <obj>.<field/method> -- field or method access, so scala thinks you want to call print(c + i) => Unit then Unit.toChar

网友答案:

The print function returns Unit, so:

print(c + i).toChar

is trying to find a toChar method for Unit (which doesn't exist).

You need to do this inside the print:

print((c + i).toChar)
# equivalently 
print(c + i toChar)
相关阅读:
Top