Generic type inference in Scala

后端 未结 1 851
感情败类
感情败类 2020-12-06 17:44

I\'ve written the following code, which is actually a dumb merge-sort implementation in scala:

import scala.collection.immutable.List

object MergeSort {
            


        
相关标签:
1条回答
  • 2020-12-06 18:40

    This is one of the most annoying Scala gotchas I can think of (maybe after semicolon inference-related issues with operators). You're three characters from the correct answer.

    The problem is the type parameter on merge. It introduces a new T that shadows the T type parameter on sort. The compiler therefore doesn't know that comparator can be applied to instances of that new T. You can boss it around with a cast, which is why your first version works, but otherwise it sees that T as a blank slate.

    Just write def merge(first: List[T], ... and you'll be fine.

    0 讨论(0)
提交回复
热议问题