varscore=// some scorevargrade=when (score) {
9, 10->"Excellent"in6..8->"Good"4, 5->"Ok"in1..3->"Fail"else->"Fail"
}
Java
for (int i =1; i <=10 ; i++) { }
for (int i =1; i <10 ; i++) { }
for (int i =10; i >=0 ; i--) { }
for (int i =1; i <=10 ; i+=2) { }
for (int i =10; i >=0 ; i-=2) { }
for (String item : collection) { }
for (Map.Entry<String, String> entry: map.entrySet()) { }
Kotlin
for (i in1..10) { }
for (i in1 until 10) { }
for (i in10 downTo 0) { }
for (i in1..10 step 2) { }
for (i in10 downTo 1 step 2) { }
for (item in collection) { }
for ((key, value) in map) { }
void doSomething(int... numbers) {
// logic here
}
Kotlin
fundoSomething(varargnumbers:Int) {
// logic here
}
Java
int getScore() {
// logic herereturn score;
}
Kotlin
fungetScore():Int {
// logic herereturn score
}
// as a single-expression functionfungetScore():Int= score
Java
int getScore(int value) {
// logic herereturn2* value;
}
Kotlin
fungetScore(value:Int):Int {
// logic herereturn2* value
}
// as a single-expression functionfungetScore(value:Int):Int=2* value
Java
publicclassUtils {
privateUtils() {
// This utility class is not publicly instantiable
}
publicstaticintgetScore(intvalue) {
return2* value;
}
}
Kotlin
class Utilsprivateconstructor() {
companion object {
fungetScore(value:Int):Int {
return2* value
}
}
}
// other way is also there
object Utils {
fungetScore(value:Int):Int {
return2* value
}
}
Java
publicclassDeveloper {
privateString name;
privateint age;
publicDeveloper(Stringname, intage) {
this.name = name;
this.age = age;
}
publicStringgetName() {
return name;
}
publicvoidsetName(Stringname) {
this.name = name;
}
publicintgetAge() {
return age;
}
publicvoidsetAge(intage) {
this.age = age;
}
@Overridepublicbooleanequals(Objecto) {
if (this== o) returntrue;
if (o ==null|| getClass() != o.getClass()) returnfalse;
Developer developer = (Developer) o;
if (age != developer.age) returnfalse;
return name !=null? name.equals(developer.name) : developer.name ==null;
}
@OverridepublicinthashCode() {
int result = name !=null? name.hashCode() :0;
result =31* result + age;
return result;
}
@OverridepublicStringtoString() {
return"Developer{"+"name='"+ name +'\''+", age="+ age +'}';
}
}
Kotlin
data class Developer(varname:String, varage:Int)
Java
publicclassUtils {
privateUtils() {
// This utility class is not publicly instantiable
}
publicstaticinttriple(intvalue) {
return3* value;
}
}
int result =Utils.triple(3);
Kotlin
fun Int.triple():Int {
returnthis*3
}
varresult=3.triple()
Useful blog
ReplyDeleteThat's full of kotlin . Very useful
ReplyDelete