Reserve words in Kotlin  

There are a number of keywords that are used by Kotlin for its internal purposes and these cannot be used as variable names and function declarations. Some of the reserve words are as follows:

in, is, as, object, val, var, for, fun, interface, when 

There are reserve words that Kotlin has reserved for itself, but when it comes to Java, most of Kotlin's reserved keywords are normal variables for Java. See the following example:

public static void is(){
System.out.println("is is a reserved keyword in Kotlin :-) ");

}

public static void var(){
System.out.println("var is a reserved keyword in Kotlin :-) ");
}

var and is are normal keywords for Java but not for Kotlin. If we need to call a function with Kotlin's reserved words, we need to use a backtick operator. See the following Kotlin example:

CallJava.`is`()
CallJava.`var`()

Use the backtick (``) operator to call Java functions whose names are reserved keyword words for Kotlin. Let's look at more examples and see how to use Java functions whose names contain Kotlin's reserved keywords.

Write a function in Kotlin that takes input from the user and displays a message on the screen. Kotlin uses a Java-provided Scanner class to take input from the keyboard, as follows:

fun inputFromKeyboard() {
println("Enter Your name .... ")
val scanner = Scanner(System.`in`)
println("My name is ${scanner.nextLine()}")
}

The Scanner class takes System.in as an input stream in order to scan input. As we can see, in is a reserved keyword but we can use this by using backticks operators. Similarly, we can use all reserved keywords as a function or variable name in this way:

fun `in`(){
println("I am in function")
}

fun `as`(){
println("I am as function")
}

fun `object`(){
println("I am object function")
}

var `var` = "Reserved keyword var"
var `object` = "Reserved keyword object"
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.177.86