Why does this Kotlin method have enclosing backticks?

走远了吗. 提交于 2019-11-26 09:50:07

问题


What are the backticks used for in the snippet below?

Why add them around the fun is(amount:Int ):Boolean { ... }?

verifier.`is`(amount)

回答1:


It's because is is a reserved keyword in Kotlin. Since Kotlin is supposed to be interoperable with Java and is is a valid method (identifier) name in Java, the backticks are used to escape the method so that it can be used as a method without confusing it as a keyword. Without it it will not work because it would be invalid syntax.

This is highlighted in the Kotlin documentation:

Escaping for Java identifiers that are keywords in Kotlin

Some of the Kotlin keywords are valid identifiers in Java: in, object, is, etc. If a Java library uses a Kotlin keyword for a method, you can still call the method escaping it with the backtick (`) character

foo.`is`(bar)



回答2:


It allows you to call a Java method whose name is a Kotlin keyword. It won't work if you leave out the backticks.




回答3:


The backtick are a "workaround" to allow you to call methods that have a name representing a Kotlin keyword.

See kotlinlang:

Some of the Kotlin keywords are valid identifiers in Java: in, object, is, etc. If a Java library uses a Kotlin keyword for a method, you can still call the method escaping it with the backtick (`) character




回答4:


is in list of Kotlin reserved words To use Kotlin reserved word (such as is or object) for function/class name you should wrap it to backticks




回答5:


Some of the Kotlin keywords are valid identifiers in Java: in, object, is, etc. If a Java library uses a Kotlin keyword for a method, you can still call the method escaping it with the backtick (`) character

https://kotlinlang.org/docs/reference/java-interop.html



来源:https://stackoverflow.com/questions/44149474/why-does-this-kotlin-method-have-enclosing-backticks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!