- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
implicit structural typing
Fri, 2010-01-08, 18:17
Hi,
I know Scala can do explicit structural typing, but I'm curious if it
could do implicit structural typing as well, e.g. something like:
---
trait A { def foo(arg: String): String }
class B { def foo(arg: String): String = arg + arg }
object Main {
def main(args: Array[String]) = {
val b = new B
structuralTypeExplicit(b)
structuralTypeImplicit(b) // won't compile even though B structurally satifies A
}
def structuralTypeExplicit(f: { def foo(arg: String): String }) = {
println(f.foo("1"))
}
def structuralTypeImplicit(f: A) {
println(f.foo("1"))
}
}
---
E.g. if the compiler noticed that B could implement A if it tried, and
just went ahead and did that for me.
The compiler could either auto-generate a delegate (Kevin? :-) or
(potentially?) use the fancy JDK feature that allows you to say, at
runtime, that, yeah, this class/instance also implements this
interface. Or something like that that I read about in a blog post and
am pretending to understand.
- Stephen
Fri, 2010-01-08, 18:57
#2
Re: implicit structural typing
> It's really only the first line that matters here, where I'm defining
> and naming a structural type in advance :)
Hehe, fair enough, I did not think of just defining A as a structural
type up-front. I'll keep that in mind.
Though, personally, I'd rather keep A as a trait (or an interface if I'm
calling into Java code), and have structural typing be a caller-side
concern of contorting my argument into the right type.
The callee-side syntax of `foo(f: def { foo() })` could then just
declare an anonymous trait, that caller-side contortions could be done
on just like any other interface-accepting method. Hence widening the
applicability of structural typing from an up-front/design-time
decision to a lazy/as-needed decision.
Perhaps that isn't a good thing, but it seems nice in my head.
- Stephen
It's really only the first line that matters here, where I'm defining and naming a structural type in advance :)(warning, I haven't actually attempted to compile this code, though I have done similar stuff in the past)
type structuralA = { def foo(arg: String): String }
class B { def foo(arg: String): String = arg + arg }
object Main {
def main(args: Array[String]) = {
val b = new B
structuralTypeExplicit(b)
structuralTypeImplicit(b)
}
def structuralTypeExplicit(f: structuralA) = {
println(f.foo("1"))
}
def structuralTypeImplicit(f: structuralA) {
println(f.foo("1"))
}
}
2010/1/8 Stephen Haberman <stephen [at] exigencecorp [dot] com>
--
Kevin Wright
mail/google talk: kev [dot] lee [dot] wright [at] googlemail [dot] com
wave: kev [dot] lee [dot] wright [at] googlewave [dot] com
skype: kev.lee.wright
twitter: @thecoda