본문으로 바로가기

2. Java Static Method equivalent in Kotlin

category Kotlin 2018. 5. 30. 15:21

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 "javasampleapproach.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);
        }
    }
}
cs


2. Equivalent in Kotlin


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 = "javasampleapproach.com"
        fun upperCase(s : String) : String = s.toUpperCase()
    }
 
    object Bar {
 
        fun bar(): String = "Bar"
    }
 
    object Num {
 
        fun doubleInt(i: Int): Int = i * 2
    }
}
cs


3. Run & Check Result


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.kotlinsample.staticmethod
 
fun main(args: Array<String>) {
 
    val static = Foo.exe()
    println(static)
    
    val upper = Foo.upperCase("javasampleapproach.com")
    println(upper)
    
    val bar = Foo.Bar.bar();
    println(bar)
    
    val num = Foo.Num.doubleInt(3);
    println(num)
}
cs



Kotlin


'Kotlin' 카테고리의 다른 글

4. Delegated Property - Observable Property  (0) 2018.05.30
3. Lazy Initialization  (0) 2018.05.30
1. Immutable & Mutable - Val vs Var  (0) 2018.05.30