|
|
|
|
|
by vvillena
2050 days ago
|
|
Scala is more strict than D for this use case. In Scala, if you want a function to be available to a certain type as if it was a method call, you need to be explicit about it. You have to declare an "implicit class" that takes the base type as an argument, and define the function as a method of the implicit class. You also need to ensure the implicit class is in scope. Once these conditions are met, you can use it as a method. val t1 = MyType()
def fun(t: MyType, argument: Int) = argument
// can't do this yet
// t1.fun(42)
// In Scala 2 you use an implicit class to add methods to a type
implicit class MyEnrichedType(t: MyType) {
def fun(argument: Int) = fun(t, argument)
}
// In Scala 3 you use an extension
extension (t: MyType)
def fun(argument: Int) = fun(t, argument)
// now it can be done
t.fun(42)
Regarding your question about the stdlib methods being able to be chained: they are not special. They are defined for the type the methods return, so they can be used.Rejecting all kinds of implicits and then complaining about Scala missing features is a bit unfair. "Implicit"is a single keyword, but not a single feature. Implicit arguments, implicit conversions and implicit classes are not the same thing. Fortunately, Scala 3 will clear this misunderstanding. |
|