This tutorial shows you a way to represent Java static method in Kotlin using Object Expression.
>>> Refer to: JavaSampleApproach.com
I. Technology
– Java 1.8
– Kotlin 1.1.2
II. Practice
1. Java static Classes and Methods
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public class Foo { public static String exe() { return "kotlination.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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Foo { companion object { fun exe(): String = "kotlination.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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.kotlination.staticmethod fun main(args: Array<String>) { val static = Foo.exe() println(static) val upper = Foo.upperCase("kotlination.com") println(upper) val bar = Foo.Bar.bar(); println(bar) val num = Foo.Num.doubleInt(3); println(num) } |
Check Result:
1 2 3 4 |
kotlination.com KOTLINATION.COM Bar 6 |