9 April 2024

Java -> Kotlin equivalents

If your starting Kotlin with prior java knowledge, here's a quick lookup table for some common equivalents:

 

Java

Kotlin

Accessibility modifiers:

  • private
  • protected
  • //default package private
  • public

     

    • private
    • protected
    • Internal // accessible in module
    • //default public

String [] anArray;

var anArray:Array<String>

(castType)

smart casting after is

as

public class Area {

private int length;

private int width;

 

//constructor

public Area(int length, int width){

this.length = length;

this.width =  width;

System.out.printf("Surface: %d",length*width);

}

 

//accessor

public int getCircumference(){

return 2*(length+width);

}

}

class Area(var length: Int , var width: Int) {

 

 

        //to add onstructor code

init {

println("Surface: ${length * width}")

}

 

 

 

 

//accessor

val circumference

get() = 2*(length + width)

 

}

anEnum.values()

anEnum.entries

class Shape{}

class Rectangle extends Shape{}

open class Shape {}

class Rectangle : Shape {}

final String aConstant="a";

val aConstant="a"

instanceOf

is

Primitives: int, double...

Int,Double...

lambda (shorter forms exist in both languages)

BiFunction<Integer, Integer, Integer> mutiply= (a, b) -> {

System.out.println("java lambda");

return a * b;

};

 

 

val multiply: (Int, Int)->Int = { a, b ->

println("kotlin lambda")

a * b

}

 

 

new Random();

Random();

Object

Any?

public static void main(String[] args){}

// Note: Java 22 has a preview of a main() function

fun main(args:Array<String>){}

static

companion

top level function

const

switch expression

when

int ternaryVar=test?1:2;

var ternaryVar = if(test) 1 else 2;

throw UnsupportedOperationException

TODO()

void

Unit

No comments:

Post a Comment