Accessing Kotlin extension functions from Java

前端 未结 9 1082
梦毁少年i
梦毁少年i 2020-11-29 21:27

Is it possible to access extension functions from Java code?

I defined the extension function in a Kotlin file.

package com.test.extensions

import c         


        
9条回答
  •  盖世英雄少女心
    2020-11-29 21:44

    Kotlin top-level extension function are compiled as Java static methods.

    Given Kotlin file Extensions.kt in package foo.bar containing:

    fun String.bar(): Int {
        ...
    }
    

    The equivalent Java code would be:

    package foo.bar;
    
    class ExtensionsKt {
        public static int bar(String receiver) { 
            ...
        }
    }
    

    Unless, that is, Extensions.kt contained the line

    @file:JvmName("DemoUtils")
    

    In which case the Java static class would be named DemoUtils

    In Kotlin, extension methods can be declared in other ways. (For example, as a member function or as an extension of a companion object.)

提交回复
热议问题