2017-10-25 14 views
1

メソッドリファレンスを使用してスーパークラスメソッドを参照するにはどうすればよいですか?スーパークラスメソッドへの参照

Java 8ではSubClass.super::methodを実行できます。

コトルの構文は何ですか?

お返事をお待ちしております。バーナード・ロシャへ

結論

ありがとう! 構文はSubClass::methodです。

ただし、注意してください。私の場合、サブクラスはジェネリッククラスでした。

MySubMap<K, V>::methodのように宣言することを忘れないでください。

EDIT

それはまだKotlinでは動作しません。

ハーズは、スーパークラスのメソッドへのメソッド参照のJavaの8の例です:

public abstract class SuperClass { 
    void method() { 
     System.out.println("superclass method()"); 
    } 
} 

public class SubClass extends SuperClass { 
    @Override 
    void method() { 
     Runnable superMethodL =() -> super.method(); 
     Runnable superMethodMR = SubClass.super::method; 
    } 
} 

私はまだKotlinで同じことを行うことができないんだけど...

EDIT

これは私がKotlinでそれを達成しようとした方法の例です:

open class Bar { 
    open fun getString(): String = "Hello" 
} 

class Foo : Bar() { 

    fun testFunction(action:() -> String): String = action() 

    override fun getString(): String { 
     //this will throw an StackOverflow error, since it will continuously call 'Foo.getString()' 
     return testFunction(this::getString) 
    } 
} 
それは不可能です

はまだKotlinにそうする

... 
    override fun getString(): String { 
     //this should call 'Bar.getString' only once. No StackOverflow error should happen. 
     return testFunction(super::getString) 
    } 
... 

結論:

は、私はそのような何かを持っていると思います。

私は機能レポートを提出しました。これは、ここで見つけることができます:KT-21103 Method Reference to Super Class Method

+0

あなたはこれをKotlinでどうしようとしていますか? –

+0

@BernardoRocha確かに。私は私の質問に例を追加しました。 – Poweranimal

答えて

3

あなたはJavaでのようにそれを使用documentation saysとして:

私たちはクラスのメンバ、または拡張機能を使用する必要がある場合、それは 修飾する必要があります。例えばString :: toCharArrayは、String型の文字列。() - > CharArrayの関数 を提供します。

EDIT

は、私はあなたがこのような何かやって欲しいものを達成することができると思う:

open class SuperClass { 
    companion object { 
     fun getMyString(): String { 
      return "Hello" 
     } 
    } 
} 

class SubClass : SuperClass() { 
    fun getMyAwesomeString(): String { 
     val reference = SuperClass.Companion 
     return testFunction(reference::getMyString) 
    } 

    private fun testFunction(s: KFunction0<String>): String { 
     return s.invoke() 
    } 
} 
1

ベルナルドの回答によると、あなたはこのようなものがあるかもしれませんが。それは顕著な変化をもたらさない。

fun methodInActivity() { 
    runOnUiThread(this::config) 
} 

fun config(){ 

} 

詳細は何ですか、入ってくる1.2バージョンでは、あなたが使用できるだけで

::config 
0
スーパークラスの関数への参照を取得することが可能であるが、ここに代わるものであれば

は知ってはいけませんあなたが達成したいもの:

override fun getString(): String = testFunction { super.getString() } 
+0

はい、私はすでにこれをやっています。しかし、私のシナリオでは、読むのがかなり醜い... – Poweranimal