Commenting out a block of code leads to a syntax error where a slash-star inside a string constant is interpreted as start of an inner block comment, which is different from C++ and Java behavior.
So in C++ no problem with block comment including myPath:
int main() {
/*
std::string myPath = “/home/*”;
std::cout <<"myPath is: " << myPath << std::endl;
*/
std::cout << “Hello, World!” << std::endl;
return 0;
}
But Kotlin gives syntax error no closing brace:
fun main(args: Array) {
/*
val myPath = “/home/*”;
println("myPath: " +myPath);
*/
println(“Hello World!”)
}
1 Like
I can confirm it’s broken, both Idea highlighting and compiler give syntax error
A workaround can be
fun main(args: Array<String>) {
/*
val myPath = "/home/${'*'}";
println("myPath: " +myPath);
*/
println("Hello World!")
}
then the commented code works the same.
1 Like
However, the behavior is correct – compiler doesn’t parse what’s inside the comment so it’s irrelevant whether it’s inside a string or not.
The reason why this happens is because kotlin (as opposed to java and c++) supports nested comments, which is useful because you can comment multiple functions which have javadocs. In java it’s impossible.
In kotlin this compiles:
/*
/**
docs
*/
fun foo() = "bar"
*/ <-- comment block ends here
in Java it doesnt:
/*
/**
docs
*/ <-- comment block ends here
fun foo() = "bar" <- not a comment
*/ <-- compile Error
Yes, the different behaviour is a “feature” of Kotlin’s nested block comment support. I just find it very surprising that star-slash sequences embedded in strings are interpreted as begin or end comment markers. Do Kotlin programmers really begin or end a comment inside string constants? Certainly the non-nested block comment behaviour of C++/Java is not preserved.
1 Like
In your example, a star-slash sequence wasn’t embedded in a string, it was inside a comment. I don’t think comments should be analysed by a compiler (aside from looking for comment block markers).
1 Like
So you’re saying C language got it wrong? 
What is surprising to me is different behaviour with heuristically the “same” code. You are saying it’s not the same because code is what the compiler sees, I think, and you are agreeing with how the Kotlin compiler sees it.
So my take away is that Kotlin block comments are in no way C/C++ style block comments. Further they are risky to use and you are better off using single line comments. Although I noticed CLion helpfully highlights occurrences of /* */ in comment blocks!
With that I agree, both for C and kotlin. TBH I have never used block comments aside from javadocs. Select, Ctrl + / . With vim plugin it’s especially convenient since you can correct selection.
1 Like