我想用Kotlin中的关键字来 减少这样的重复代码量:
fun printAlphabet() = with(StringBuilder()){
for (letter in 'A'..'Z'){
append(letter)
}
toString()
}
有什么设施吗?
答案 0 :(得分:2)
您可以使用With
这样的方法来做到这一点:
// you need a separate overload to handle the case of not returning anything
public static void With<T>(T t, Action<T> block) {
block(t);
}
public static R With<T, R>(T t, Func<T, R> block) => block(t);
然后您可以using static
声明方法的类,并像这样使用它(here的翻译代码):
var list = new List<string> {"one", "two", "three"};
With(list, x => {
Console.WriteLine($"'with' is called with argument {x}");
Console.WriteLine($"It contains {x.Count} elements");
});
var firstAndLast = With(list, x =>
$"The first element is {x.First()}. " +
$"The last element is {x.Last()}.");
在您的示例中,它将像这样使用:
static string PrintAlphabet() => With(new StringBuilder(), x => {
for (var c = 'A' ; c <= 'Z' ; c = (char)(c + 1)) {
x.Append(c);
}
return x.ToString();
});