MPS 2026.1 ヘルプ

型拡張メソッド

Jetbrains.mps.baseLanguage.extensionMethods 言語は、Java の静的メソッドに似た、新しく定義されたメソッドまたはオーバーライドされたメソッドを使用して有効な MPS 型を拡張する方法を提供します。

"This is an ordinary string with a surprising behavior!".myNewMethod() "Develop with pleasure!".isAPleasureMessage() int num = ... num.isPrime()

静的メソッドは拡張クラスの内部部分になることはなく、拡張メソッドのパラメーターの 1 つとして操作する「拡張」オブジェクトを常に指定する必要がありますが、拡張メソッドでは、新しいメソッドがターゲット型で使用可能な操作のリストに直接追加されます。

古き良き「静的メソッド」の方法ではなく、文字列型にメソッドを追加したい場合は、次のようになります。

public static string reverse(string target) { //reverse the target }

New-> jmbaseLanguage.extensionMethods/type extension を使用して新しい拡張メソッドを作成し、新しいメソッドを定義して文字列クラスに関連付けます。

public extension methods MySampleMethods for string { <<static fields>> public string reverse() { //reverse the string, referring to it through 'this' } }

まったく同じメカニズムを使用して、既存のメソッドをオーバーライドできます。そして、元のメソッドを呼び出す必要がある場合は、これで呼び出すだけです:

 public extension methods MySampleMethods for string { <<static fields>> public string trim() { this.trim() + " trimmed" //calls the original trim() implementation } }

Since MPS does a good job of visually distinguishing original and overridden methods through the extension methods mechanism, you can't make a mistake picking the right one from the drop-down list.

extension-methods1.png

明らかに、このメカニズムを使用して、独自のドメインオブジェクトに直交概念を実装することもできます。

public extension methods Sample for my_type { <<static fields>> public int foo() { return this.bar(); } }

上記の宣言を使用すると、タイプ my_type で操作を記述できます。

my_type var = ...; var.foo();

ルートノード

There are two equally good ways to extend types with methods. Type Extension allows you to add methods to a single type in one place, while Simple Extension Method Container comes in handy, when you need one place to implement an orthogonal concept for multiple different types.

タイプの拡張

このルートには単一型の拡張メソッドの宣言が含まれています。

[public|protected|private] extension methods containerName for extendedType { <<static fields>> <<extension methods>> }

拡張メソッド宣言

public ret_Type methodName() { <no statements> }

単純拡張メソッドコンテナー

[public|protected|private] extension methods containerName { <<static fields>> <<extension methods>> }

拡張メソッド宣言ターゲットタイプはメソッドごとに指定されます。

public ret_type methodName() for extendedType { <no statements> }

宣言部

許可された内容

containerName

任意の有効な識別子

extendedType

任意の有効な MPS タイプ

両方の根は 1 つ以上の静的フィールドを含むことができます。これらはコンテナー内のすべてのメソッドで利用可能です。

2026 年 5 月 06 日