
Here are three ways to comment out code in Kotlin and an example code.
1. Single line comment
You can write a single comment by using double slash (//) .
Used to write single-line comments.
Example code 1 :
/// This line is comment outed /// This line is also comment outed
Example code 2 :
/// Define variable fizz val fizz = 1234 /// Add 100 to fizz fizz += 100
2. Multiple lines comment
You can write multiple lines comment by using /*…*/ syntax.
Example code 1 :
/** * Those lines are comment outed. **/
Example code 2 :
/* * /// Comment out codes * var fizz = 123 * fizz += 456 */
It is useful for commenting out multiple lines of code and annotating methods, classes, variables, processes, etc.
3. Python style comment
In fact, you can also use Python-like commenting out in Kotlin.
It’s a multi-line comment with a string literal.
See the some sample codes below…
Example code 1 :
/// Comment by string literal """ This line is comment outed. This line is also comment outed. """
Example code 2 :
/// Comment out multiple codes """ var fizz = 123 fizz += 456 """
For normal comment-out, the aforementioned comment-out methods are sufficient. There are usually no situations where Python-style comment-out is needed.
How python style comment is used?
However, if you include /* or */ in your code, you cannot comment out multiple lines. For example, the following code contains a MIME type
Example code (Not works) :
/* var mimeType = "*/*" // ^ Not correct!! System.out.println("MIME type is...") if(mimeType.startsWidth("image")){ System.out.println("Image") }else{ System.out.println("Not image") } */
As you can see from the highlight above, */* is interpreted as the end of the comment.
Python-style comments are useful in these cases.
Example code (Works) :
/// Fixed to python style comment """ var mimeType = "*/*" // ^ Works correctly!! System.out.println("MIME type is...") if(mimeType.startsWidth("image")){ System.out.println("Image") }else{ System.out.println("Not image") } """
Works correctly.
Thank you for another fantastic post. Where else could anyone get that type of information in such an ideal way of writing? I’ve a presentation next week, and I am on the look for such information.
When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get three emails with the same comment. Is there any way you can remove people from that service? Cheers!