Type mismatch on abstract type used in pattern matching

前端 未结 3 1201
夕颜
夕颜 2020-12-03 11:25

This code compiles with an error:

def f1[T](e: T): T = e match {
  case i:Int => i
  case b:Boolean => b
}
// type mismatch;
// found   : i.type (with          


        
3条回答
  •  北海茫月
    2020-12-03 12:29

    In addition to @Esardes answer, this worked by defining a type bound for T:

    scala> def f1[T >: AnyVal](e: T):T = e match {
         |   case i:Int => i
         |   case b:Boolean => b
         | }
    f1: [T >: AnyVal](e: T)T
    
    scala> f1(1)
    res3: AnyVal = 1
    
    scala> f1(true)
    res4: AnyVal = true
    

提交回复
热议问题