2016-11-04 9 views
1

現在、何回かパス依存型で解決できるはずの問題が発生しましたが、それで最も完全で正しい方法で。 Javaの世界では、ネイティブ・タイプにマップされるクローズド・セットを定義する列挙型(静的な値の形で擬似列挙さえもある)を持つことは珍しいことではありません。私は彼らのネイティブ型にこれらの列挙型から私を取るいくつかのマッピングを提供したいと思いスカラは、パスに依存する型を持つネイティブ型に列挙します

public class Types { 

    /** 
    * <P>The constant in the Java programming language, sometimes referred 
    * to as a type code, that identifies the generic SQL type 
    * <code>BIT</code>. 
    */ 
    public final static int BIT    = -7; 

    /** 
    * <P>The constant in the Java programming language, sometimes referred 
    * to as a type code, that identifies the generic SQL type 
    * <code>TINYINT</code>. 
    */ 
    public final static int TINYINT   = -6; 

    /** 
    * <P>The constant in the Java programming language, sometimes referred 
    * to as a type code, that identifies the generic SQL type 
    * <code>SMALLINT</code>. 
    */ 
    public final static int SMALLINT  = 5; 
    // ... 
} 

java.sql.Typesが良い例です。私は手を前に、具体的なSqlTypeインスタンスを取得し、適切なパス依存を取得するには、関数の引数としてそれを渡す必要があり、これは、しかし、少しグラグラです

import java.sql.{Types, ResultSet} 

trait SqlType { 
    def typeValue:Int 
    type Value 
    def getValue(rs:ResultSet, idx:Int):Value 
} 

object SqlType { 

    object SqlInt extends SqlType { 
    type Value = Int 
    def typeValue = Types.INTEGER 
    def getValue(rs:ResultSet, idx:Int) = rs.getInt(idx) 
    } 

    object SqlString extends SqlType { 
    type Value = String 
    def typeValue = Types.NVARCHAR 
    def getValue(rs:ResultSet, idx:Int) = rs.getString(idx) 
    } 


    def getSqlType(typeValue:Int):SqlType = typeValue match { 
    case Types.INTEGER => SqlInt 
    case Types.NVARCHAR => SqlString 
    } 

    implicit class ResultSetExtras(rs:ResultSet) { 
    def getCell(idx:Int, sqlType:SqlType):sqlType.Value = sqlType.getValue(rs, idx) 
    } 
} 

:これまでのところ私はこのようなものを持っていますタイプ。

implicit class ResultSetExtras2(rs:ResultSet) { 
    def getCell2(idx:Int):SqlType#Value = getSqlType(rs.getMetaData.getColumnType(idx)).getValue(rs, idx) 
    } 

は(SqlType#Valueの戻り値の型ではなく、パス依存sqlType.Valueの点に注意してください。(良くあります:私はこのような何かを行うことができますようだから、私が本当に欲しいものをしている、いないようです私は、シェイプレスやマクロのようなものが助けになるかもしれないと思っていますが、可能であれば、パスに依存するタイプ(あるいはシェイプレスでないものよりも実際にはマクロ)が可能かどうかを知りたいです。

答えて

1

問題は、コンパイル時にの場合はrs.getCell(2)の場合は不可能であり、正確な具体的なタイプの値が生成されることを知ることです。 ypesはここで助けません。結果のタイプは実行時にとしか知られていません。戻り値として抽象タイプSqlTypeを選択すると問題はありません(Javaの場合と同じです)。実際にタイプをSqlType#Valueで表すことはできません。

関連する問題