I have defined a method in a trait:
trait myTrait {
def myMethod(entity: Entity = null, name: String)
}
val t = ....//concrete implementation of myTrait
t.myMethod("John")
I have provided default value of null for entity in method definition.
This give compilation error as: Type mismatch, required MyCustomClass found String
Why is it so?
CodePudding user response:
Use the name of your argument.
t.myMethod(name = "John")
It also works for case class when you want to .copy
case class MyStruct(a: String, b: String)
val a = MyStruct("foo", "bar")
val b = a.copy(b = "clazz")
See https://docs.scala-lang.org/tour/named-arguments.html
Also, in scala, the presence / absence of value is usually represented by Option[T]
like
def myMethod(entity: Option[Entity] = None, ... )