Kotlin – Java Static Method equivalent in Kotlin

This tutorial shows you a way to represent Java static method in Kotlin using Object Expression.

I. Technology

– Java 1.8
– Kotlin 1.1.2

II. Practice

1. Java static Classes and Methods


public class Foo {

	public static String exe() {
		return "grokonez.com";
	}

	public static String upperCase(String s) {
		return s.toUpperCase();
	}

	public static class Bar {

		public static String bar() {
			return "Bar";
		}
	}

	public static class Num {

		public static Integer doubleInt(Integer i) {
			return new Integer(i.intValue() * 2);
		}
	}
}

2. Equivalent in Kotlin

Using Kotlin Object Expression, we can make “static” Equivalent:


class Foo {

	companion object {

		fun exe(): String = "grokonez.com"
		fun upperCase(s : String) : String = s.toUpperCase()
	}

	object Bar {

		fun bar(): String = "Bar"
	}

	object Num {

		fun doubleInt(i: Int): Int = i * 2
	}
}

3. Run & Check Result

Run the code below:


package com.javasampleapproach.staticmethod

fun main(args: Array) {

	val static = Foo.exe()
	println(static)
	
	val upper = Foo.upperCase("grokonez.com")
	println(upper)
	
	val bar = Foo.Bar.bar();
	println(bar)
	
	val num = Foo.Num.doubleInt(3);
	println(num)
}

Check Result:


grokonez.com
grokonez.com
Bar
6


By grokonez | August 29, 2017.

Last updated on April 16, 2021.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*