You can use type ascription to circumvent some checks in Scala compiler but you’ll stumble upon other (which are pretty sensible this time):
sealed trait DSL[A] {
def run(): A ={
(this: DSL[_]) match {
case GetLength(something) =>
// type mismatch; found: Int; required: A
something.length
case ShowResult(number) =>
// type mismatch; found: String; required: A
s"the length is $number"
}
}
}
case class GetLength(something: String) extends DSL[Int]
case class ShowResult(number: Int) extends DSL[String]
Overall the above code follows neither OOP nor FP idioms. A parent class (or trait) shouldn’t know implementation details about child classes (or traits). If you want OOP make def run()
abstract. If you want FP put def run()
into a companion object.
BTW:
This also fails to compile:
sealed trait DSL[A]
case class GetLength(something: String) extends DSL[Int]
case class ShowResult(number: Int) extends DSL[String]
def run[A](fa:DSL[A]): A ={
fa match {
case GetLength(something) =>
something.length
case ShowResult(number) =>
fa match {
case GetLength(something) =>
// type mismatch; found: Int; required: A
something.length
case ShowResult(number) =>
s"the length is $number"
}
}
}
@tarsa Thanks, I get what you mean. I am trying to understand the natural transformation in the free-monad which follows F[_] => G[_]
. Not a real case that I want use for some design.
this can work like code outside the trait as a generic method, but I just curious why this not work like the way in the trait itself.
Is this a design consideration or a bug to behavior different in type argument?
seems something like this : https://gist.github.com/smarter/2e1c564c83bae58c65b4f3f041bfb15f
There’s nothing about pattern matching on this
in that article.
Not sure I would say the workaround (additional method to convert
this
to a method parameter) is simple and compact enough for people to not care about the original case. I think the way you described the problem originally suggest that it’s just you wondering how to do a thing instead of pointing a finger on a bug, hence the compiler guys skipped your request.